숨박꼭질 4 - 골드 4 (백준, BFS)

2023. 1. 20. 16:00코딩 테스트 준비

728x90
반응형
from collections import deque

N, K = map(int, input().split())
road = [0] * 100001
move = [0] * 100001

def path(x):
    arr = []
    temp = x
    for _ in range(road[x]+1):
        arr.append(temp)
        temp = move[temp]
    print(' '.join(map(str, arr[::-1])))
  
def bfs():
  q = deque()
  q.append(N)
  while q:
    x = q.popleft()
    if x == K:
        print(road[x])
        path(x)
        break
    for dx in (x*2, x+1, x-1):
      if 0 <= dx <= 100000 and road[dx] == 0:
          q.append(dx)
          road[dx] = road[x]+1
          move[dx] = x
    
bfs()​

위의 코드는 틀렸다고 나오는데 아래의 코드는 맞다고 나온다 이유가 뭘까...?

from collections import deque

def path(x):
    arr = []
    temp = x
    for _ in range(dist[x]+1):
        arr.append(temp)
        temp = move[temp]
    print(' '.join(map(str, arr[::-1])))

def bfs():
    q = deque()
    q.append(N)
    while q:
        x = q.popleft()
        if x == K:
            print(dist[x])
            path(x)
            return x
        for i in (x+1, x-1, 2*x):
            if 0<=i<=100000 and dist[i]==0:
                q.append(i)
                dist[i] = dist[x] + 1
                move[i] = x

N, K = map(int, input().split())
dist = [0]*100001
move = [0]*100001
bfs()

누군가 본다면 제발 알려주시길..

728x90
반응형