BOJ 13549 숨바꼭질 3

1 개요[ | ]

BOJ 13549 숨바꼭질 3

2 같이 보기[ | ]

3 C++[ | ]

#include <bits/stdc++.h>
#include <limits.h>
using namespace std;

int N, K;
int visited[100001];

int bfs() {
    queue<int> q;
    q.push(N);
    visited[N] = 1;
    int x, nx, ncost;
    while(!q.empty()) {
        x = q.front();
        q.pop();
        if(x == K) return visited[x];
        for(int i=0; i<3; i++) {
            if(i==0) {
                nx = x*2;
                ncost = 0;
            } else if(i==1) {
                nx = x+1;
                ncost = 1;
            } else {
                nx = x-1;
                ncost = 1;
            }
            if(nx<0 || nx>100000 || visited[nx]<visited[x]+ncost) continue;
            visited[nx] = visited[x]+ncost;
            q.push(nx);
        }
    }
    return -1;
}

int main() {
    cin >> N >> K;
    fill(visited, visited+100001, INT_MAX);
    cout << bfs()-1;
}