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

BOJ 2252 - ์ค„ ์„ธ์šฐ๊ธฐ

by HandHand 2021. 6. 7.

๋ฌธ์ œ

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

ํ’€์ด ๊ณผ์ •

์œ„์ƒ ์ •๋ ฌ ์„ ํ™œ์šฉํ•œ ํ•ด๋ฒ•์œผ๋กœ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.
๋‹ค์–‘ํ•œ ๋ฐฉ๋ฒ•์ด ์žˆ์ง€๋งŒ DFS ๋ฅผ ํ™œ์šฉํ•ด ์œ„์ƒ ์ •๋ ฌ ์„ ๊ตฌํ˜„ํ•˜๋Š” ๊ฒƒ์ด ๊ฐ€์žฅ ๊ฐ„๋‹จํ•ด์„œ ์ด ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค.

์ฝ”๋“œ


import sys

n, m = list(map(int, sys.stdin.readline().split()))
adj = [[] for _ in range(n+1)]
for _ in range(m):
    frm, to = list(map(int, sys.stdin.readline().split()))
    adj[frm].append(to)


def dfs(here, visit, ans):
    visit[here] = 1

    for there in adj[here]:
        if not visit[there]:
            dfs(there, visit, ans)

    ans.append(here)


def solution():
    ans = []
    visit = [0 for _ in range(n+1)]
    for i in range(1, n+1):
        if not visit[i]:
            dfs(i, visit, ans)

    ans.reverse()
    return ' '.join(map(str, ans))


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

๐Ÿ’ฌ ๋Œ“๊ธ€