๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/boj

BOJ 18352 - ํŠน์ • ๊ฑฐ๋ฆฌ์˜ ๋„์‹œ ์ฐพ๊ธฐ

by HandHand 2021. 3. 18.

๋ฌธ์ œ

๋ฐฑ์ค€ ์˜จ๋ผ์ธ ์ €์ง€ - 18352๋ฒˆ

ํ’€์ด ๊ณผ์ •

ํŠน์ • ์ง€์ ์—์„œ ๋ชฉํ‘œ ์ง€์ ์— ๋„๋‹ฌํ•˜๊ธฐ ์œ„ํ•œ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๋“ค ์ค‘์—์„œ K ์ธ ์ •์ ๋“ค์„ ์ฐพ๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

์ฒ˜์Œ์—๋Š” ๋‹จ์ˆœํ•œ BFS ๋ฌธ์ œ์ธ์ค„ ์•Œ๊ณ  ์ ‘๊ทผํ–ˆ๋‹ค๊ฐ€ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•˜๋Š” ์‹œ์  ๋•Œ๋ฌธ์— ์ž๊พธ ์˜ค๋‹ต์ด ๋ฐœ์ƒํ•ด์„œ ์‚ฝ์งˆ์„ ํ•˜๋‹ค๊ฐ€

๋‹ค์ต์ŠคํŠธ๋ผ ๋กœ ๋‹ค์‹œ ์ ‘๊ทผํ•ด์„œ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ–ˆ์Šต๋‹ˆ๋‹ค.

์ฝ”๋“œ


import sys
from collections import deque

N, M, K, X = list(map(int, sys.stdin.readline().split()))
edges = [list(map(int, sys.stdin.readline().split())) for _ in range(M)]


def make_graph():
    graph = [[] for _ in range(N + 1)]

    for frm, to in edges:
        graph[frm].append(to)

    return graph


def bfs(graph):
    answer, q = [], deque()
    dist = [-1] * (N + 1)

    dist[X] = 0
    for near in graph[X]:
        q.append(near)
        dist[near] = 1

    while q:
        here = q.popleft()

        for there in graph[here]:
            if dist[there] == -1:
                dist[there] = dist[here] + 1
                q.append(there)

    for there in range(1, N + 1):
        if dist[there] == K:
            answer.append(there)

    return answer if answer else [-1]


def solution():
    graph = make_graph()
    answer = bfs(graph)

    print(*answer, sep='\n')


solution()
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > boj' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

BOJ 3184 - ์–‘  (0) 2021.03.18
BOJ 7562 - ๋‚˜์ดํŠธ์˜ ์ด๋™  (0) 2021.03.18
BOJ 16173 - ์ ํ”„์™• ์ฉฐ๋ฆฌ(small)  (0) 2021.03.18
BOJ 2096 - ๋‚ด๋ ค๊ฐ€๊ธฐ  (0) 2021.03.18
BOJ 14716 - ํ˜„์ˆ˜๋ง‰  (0) 2021.03.18

๐Ÿ’ฌ ๋Œ“๊ธ€