๊ณจ๋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 ๋ฐฑ์ค(13913๋ฒ) - ์จ๋ฐ๊ผญ์ง4