문제풀이/DFS & BFS

[파이썬!] [BFS] 백준 1697 숨바꼭질

승무_ 2022. 1. 12. 08:56

문제 정의

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

 

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

 

 

입력

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

 

 

출력

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

 

 

예제 입력 1

5 17

 

예제 출력 1

4

코드

#include <iostream>
#include <queue>

using namespace std;

int main()
{
    queue<int> q;
    int visited[200000]={0, };
    int x;
    int y;
    cin>>x>>y;
    
    q.push(x);
    while(!q.empty()){
        int temp=q.front();
        q.pop();
        if(temp==y) break;
        if(temp-1>=0 && visited[temp-1]==0){
            visited[temp-1]+=visited[temp]+1;
            q.push(temp-1);
        }
        if(temp+1<=100000 && visited[temp+1]==0){
            visited[temp+1]+=visited[temp]+1;
            q.push(temp+1);
        }
        if((temp*2)<=100000 && visited[temp*2]==0){
            visited[temp*2]+=visited[temp]+1;
            q.push(temp*2);
        }
    }
    cout<<visited[y];
    return 0;
}
from collections import deque
queue=deque()

def bfs():
    queue.append(n)
    while queue:
        x=queue.popleft()
        if x==k:
            print(visited[k])
            break
        
        for j in (x-1,x+1,x*2):
            if 0<=j<100001 and visited[j]==0:
                visited[j]=visited[x]+1
                queue.append(j)
            
            
n,k=map(int, input().split())
visited=[0]*100001
bfs()