ALDS_11_B – 深さ優先探索

AtCoderなど過去問

ALDS_11_B – 深さ優先探索

import sys

n = int(input())
v = []
for i in range(n):
 v.append([int(s) for s in sys.stdin.readline().split()[2:]])

d = [0] * n
f = [0] * n
now = 0

def dfs(s,now):
    now += 1
    d[s] = now
    
    for i in v[s]:
        j = i-1
        if d[j]:continue
        now = dfs(j,now)
    now += 1
    f[s] = now
    return now


for s in range(n):
    if d[s]:continue
    now = dfs(s,now)

for i in range(n):
    print(i+1,d[i],f[i])

コメント

タイトルとURLをコピーしました