BOJ - 18352 - 특정 거리의 도시 찾기

Updated:

import sys
from collections import deque

def Dijkstra(N, K, X, graph):
    visit = [False] * (N + 1)
    dq = deque()
    dq.append((X, 0))
    visit[X] = 0

    while dq:
        vertex, weight = dq.popleft()
        for v in graph[vertex]:
            if visit[v] is False:
                visit[v] = weight + 1
                dq.append((v, weight + 1))

    ret = []
    for i in range(len(visit)):
        if visit[i] == K:
            ret.append(i)

    if not ret:
        print(-1)
        return
    ret.sort()
    for i in ret:
        print(i)

def solution():
    N, M, K, X = map(int, sys.stdin.readline().split())
    graph = [[] for _ in range(N+1)]
    for _ in range(M):
        A, B = map(int, sys.stdin.readline().split())
        graph[A].append(B)

    Dijkstra(N, K, X, graph)

solution()

https://www.acmicpc.net/problem/18352

Categories:

Updated:

Leave a comment