알고리즘/문제풀이

백준 1697 - 숨바꼭질 (그래프 순회, 탐색 , 최단경로와 BFS)

ebang 2022. 12. 28. 23:00
반응형

문제

수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일 때 걷는다면 1초 후에 X-1 또는 X+1로 이동하게 된다. 순간이동을 하는 경우에는 1초 후에 2*X의 위치로 이동하게 된다.

수빈이와 동생의 위치가 주어졌을 때, 수빈이가 동생을 찾을 수 있는 가장 빠른 시간이 몇 초 후인지 구하는 프로그램을 작성하시오.

입력

첫 번째 줄에 수빈이가 있는 위치 N과 동생이 있는 위치 K가 주어진다. N과 K는 정수이다.

출력

수빈이가 동생을 찾는 가장 빠른 시간을 출력한다.

 

 

 

1. 문제 해석

수빈이가 동생의 위치에 도달할 때까지 최소한으로 이동하는 횟수를 구하는 것과 같다. 

1회 이동 시에 수빈이의 위치는 +1 , -1 혹은 *2 될 수 있다.

 

수빈이가 갈 수 있는 위치에 대해 그 위치에 도달 할 때까지 걸릴 수 있는 시간 중 최소를 각 배열에 저장해 둔다면, (모든 배열에 대해 수행)

동생 위치까지 도달하는 데 걸리는 시간도 구할 수 있을 것이다. 

 

2. 구현

2.1. 의사코드

max = MAX(동생 , 수빈)

1. 초기화
for(int i=0;i<=max;i++)
{
	time[i] = INF;
}

2. v <- 수빈 , time[수빈] = 0, Q.push(v)
3. BFS(v) : 
while(!Q.isEmpty())
    node <- Q.pop()
	for each w in adjacent(node): 
		if(Cango(W) && !visited(w)):
        		Q.push(v)
	        	time(v) <- min(time(v), time(node) + 1)

2.2 구현한 코드

#include <iostream>
#include <queue>

using namespace std;
int map[100001];
int dis[100001];
int N,K,max_;

queue <int> Q;

int Cango(int i)
{
    if(i < 0 || i > max_)
        return 0;
    return 1;
}

void BFS()
{
    while(!Q.empty())
    {
        int current = Q.front();
        //printf("in BFS: %d, dis = %d\n", current, dis[current]);
        Q.pop();
        if (Cango(current + 1))
        {
            if(dis[current + 1] == -1 || dis[current + 1] > dis[current] + 1) {
                dis[current + 1] = dis[current] + 1;
                Q.push(current+1);
            }
        }
        if (Cango(current - 1))
        {
            if(dis[current - 1] == -1 || dis[current - 1] > dis[current] + 1) {
                dis[current - 1] = dis[current] + 1;
                Q.push(current-1);
            }
        }
        if (Cango(current*2))
        {
            if(dis[current*2] == -1 || dis[current*2] > dis[current] + 1) {
                dis[current * 2] = dis[current] + 1;
                Q.push(current*2);
            }
        }
    }
}

int MAX(int n, int k)
{
    return n>k?n:k;
}

void init()
{
    for(int i=0;i<=max_; i++)
    {
        dis[i] = -1;
    }
}
int main()
{
    scanf("%d %d", &N, &K);
    max_ = MAX(N,K) +1;
    init();
    Q.push(N);

    dis[N] = 0;
    BFS();
    printf("%d", dis[K]);

}
반응형