728x90
반응형

기본적인 BFS 문제이다. 

from collections import deque

def bfs(node):
    q = deque()
    q.append(node)
    check[node] = 0
    while q:
        node = q.popleft()
        for n in graph[node]:
            if check[n] == -1:
                check[n] = check[node]+1
                q.append(n)

N, M, K, X = map(int, input().split())
graph = [[] for _ in range(N+1)]
check = [-1]*(N+1)
for _ in range(M):
    u, v = map(int, input().split())
    graph[u].append(v)
bfs(X)
if K not in check:
    print(-1)
else:
    for i in range(N+1):
        if check[i] == K:
            print(i)
728x90
반응형

+ Recent posts