알고리즘

BOJ #1697 : 숨바꼭질 (BFS의 최단경로 길이)

숨바꼭질

전체 코드

#include <cstdio>
#include <vector>
#include <queue>

using namespace std;

const int MAX_NODE = 100001;
int n, k;
int answer = 0;
int visited[MAX_NODE];
vector<int> edge[MAX_NODE];

int bfs(int pos);

int main()
{
    scanf("%d %d", &n, &k);
    for(int i = 0; i < MAX_NODE - 1; i++)
    {
        edge[i].push_back(i + 1);
        edge[i + 1].push_back(i);
    }
    for(int i = 1; i <= MAX_NODE/2; i++)
    {
        edge[i].push_back(2 * i);
    }
    printf("%d", bfs(n));
}   


int bfs(int pos)
{   
    queue<int> q;
    q.push(pos);
    visited[pos] = 1;
    int size = 0;

    while(!q.empty())
    {
        if (size == 0) size = q.size();
        int now  = q.front();
        q.pop();
        size -= 1;

        if (now == k)
        { 
            return answer;
        }

        if (size == 0){
            answer += 1;
            }

        for (auto next : edge[now])
        {
            if (visited[next] == 0)
            {   
                visited[next] = 1;
                q.push(next);
            }
        }
    }
}