백준 13913 - 숨바꼭질 4 (파이썬)

Updated:

Answer

import sys
from collections import deque

input = sys.stdin.readline
N, K = map(int, input().split())
MAX = 100001
dp = [0] * MAX
path = [0] * MAX

def bfs():
    q = deque([N])

    while q:
        x = q.popleft()

        if x == K:
            print(dp[K])
            return
        
        for i in (x + 1, x - 1, x * 2):
            if -1 < i < MAX and dp[i] == 0:
                dp[i] = dp[x] + 1
                path[i] = x
                q.append(i)

def find_path():
    answer = []
    tmp = K
    
    for _ in range(dp[K] + 1):
        answer.append(tmp)
        tmp = path[tmp]
    
    print(*answer[::-1])
    
bfs()
find_path()

Categories:

Updated: