[BFS] 특정 거리의 도시 찾기

yejichoi·2023년 9월 19일
0

알고리즘 스터디

목록 보기
100/153
post-thumbnail

출처 : 이코테

from collections import deque

n, m, k, x = map(int, input().split())
graph = [[] for _ in range(n+1)] #인덱스값 맞추기 위해 n+1
print(graph) # [[], [], [], [], []]
for _ in range(m):
  a, b = map(int, input().split())
  graph[a].append(b)
print(graph) #  [[], [2, 3], [3, 4], [], []]
distance = [-1] * (n+1)
distance[x] = 0
print(distance) # [-1, 0, -1, -1, -1]
q = deque([x])
while q:
  now = q.popleft() # 1, 3, 2
  for next_node in graph[now]: # next_node = [2,3], [3,4]
    if distance[next_node] == -1:
      distance[next_node] = distance[now] + 1
      q.append(next_node)

check = False
for i in range(1, n+1):
  if distance[i] == k:
    print(i)
    check = True

if check == False:
  print(-1)

0개의 댓글