๊ณจ๋“œ5 : BFS ๋ฌธ์ œ์ด๋‹ค.

ํ’€์ด

BFS์—์„œ ์ตœ๋‹จ๊ฑฐ๋ฆฌ๋ฅผ ์ฐพ์€ ํ›„ ๋’ค์— ํƒ์ƒ‰์„ ํ•˜์ง€ ์•Š๋Š” ๋ฐฉ๋ฒ•

Code

from collections import deque
import sys
 
input = sys.stdin.readline
MAXNUM = 1e6
N, K = map(int, input().split())
visited = [False] * int(MAXNUM + 1)
minTime, minTimeNumOfVisited = 1e6, 0
 
def BFS():
    global minTime, minTimeNumOfVisited
    q = deque()
    q.append((N, 0))
 
    while q:
        pos, time = q.popleft()
        visited[pos] = True
 
        if time > minTime:
            continue  # ์• ์ดˆ์— ํ˜„์žฌ๊ฑธ๋ฆฐ์‹œ๊ฐ„์ด ์ตœ์†Œ์‹œ๊ฐ„๋ณด๋‹ค ํฌ๋ฉด ํƒ์ƒ‰ํ•  ์ด์œ ๊ฐ€ ์—†์Œ
 
        if pos == K:
            minTime = min(minTime, time)  # ์ฒ˜์Œ ๋ฐฉ๋ฌธํ•˜๋ฉด ์—ฌ๊ธฐ์„œ ๊ฑธ๋ฆฌ๊ฒŒ ๋˜์–ด์žˆ์Œ
            minTimeNumOfVisited += 1
 
        nexts = [(pos - 1, time + 1), (pos + 1, time + 1), (2 * pos, time + 1)]
        for npos, ntime in nexts:
            if 0 <= npos <= MAXNUM and visited[npos] == False:
                q.append((npos, ntime))
 
BFS()
print(minTime)
print(minTimeNumOfVisited)

Reference