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

ํ’€์ด

์•„๋‹ˆ ํ’€์ด๋ฐฉ๋ฒ•์„ ์•„๋Š”๋ฐ ์™œ ์ฝ”๋“œ๊ฐ€ ์•ˆ๋Œ์•„๊ฐ€๋Š”์ง€ ๋ชจ๋ฅด๊ฒ ๋‹ค. ๊ณ„์†ํ•ด์„œ ๋ฉ”๋ชจ๋ฆฌ ์ดˆ๊ณผ๊ฐ€ ๋œจ๋Š”๋ฐ ์–ด๋–ค ๋ถ€๋ถ„์ด ๋ฌธ์ œ์ธ์ง€ ์•„์ง๋„ ๋ชป์ฐพ์•˜๋‹ค..

Code

from collections import deque
import sys
 
# sys.setrecursionlimit(int(1e6))
# input = sys.stdin.readline
 
N, K = map(int, input().split())
visited = [-1] * 100001
path = []
 
 
def BFS():
    q = deque()
    q.append((N, 0))
    visited[N] = N
 
    while q:
        pos, time = q.popleft()
        if pos == K:
            a = pos
            while a != N:
                path.append(a)
                a = visited[a]
            path.append(a)
            return time
 
        if pos + 1 < 100001 and visited[pos + 1] == -1:
            q.append((pos + 1, time + 1))
            visited[pos + 1] = pos
 
        if pos - 1 >= 0 and visited[pos - 1] == -1:
            q.append((pos - 1, time + 1))
            visited[pos - 1] = pos
 
        if pos * 2 < 100001 and visited[pos * 2] == -1:
            q.append((pos * 2, time + 1))
            visited[pos * 2] = pos
 
 
print(BFS())
print(path[::-1])
 
 
 
from collections import deque
import sys
 
n, k = map(int, input().split())
 
visited = [-1] * 100001  # ๋ฐฉ๋ฌธ์—ฌ๋ถ€๊นŒ์ง€ ํ™•์ธํ•˜๊ธฐ ์œ„ํ•ด -1๋กœ ์ดˆ๊ธฐํ™”
path = []  # ์ง€๊ธˆ๊นŒ์ง€ ๋ฐฉ๋ฌธ ๊ฒฝ๋กœ ์ €์žฅ
 
 
def bfs(start, target):
    queue = deque()
    queue.append((n, 0))
    visited[start] = start
    while queue:
        cur, cur_time = queue.popleft()
        if cur == target:  # ๋™์ƒ์„ ์ฐพ์Œ
            idx = cur
            while idx != start:
                path.append(idx)
                idx = visited[idx]  # ์ด ๋ถ€๋ถ„์ด ์ค‘์š”!
            path.append(start)  # ์ฒซ ์‹œ์ž‘์ ๊นŒ์ง€ ๋„ฃ๋Š”๋‹ค
            return cur_time
        if cur + 1 < 100001 and visited[cur + 1] == -1:
            queue.append((cur + 1, cur_time + 1))
            visited[cur + 1] = cur
 
        if cur - 1 >= 0 and visited[cur - 1] == -1:
            queue.append((cur - 1, cur_time + 1))
            visited[cur - 1] = cur
 
        if cur * 2 < 100001 and visited[cur * 2] == -1:
            queue.append((cur * 2, cur_time + 1))
            visited[cur * 2] = cur
 
 
print(bfs(n, k))
print(*path[::-1])  # ๋’ค์—์„œ ๋ถ€ํ„ฐ ์ถœ๋ ฅ
 
 
# ์œ„์˜ ์ฝ”๋“œ๊ฐ€ ์™œ์•ˆ๋˜๋Š”์ง€ ๋š2ใ…“ํžˆ ์•Œ ์ˆ˜๊ฐ€ ์—†๋‹ค.

Reference