ALDS_11_C – 幅優先探索

AtCoderなど過去問

ALDS_11_C – 幅優先探索

import sys

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



def bfs(s):
    que = []
    dist = [-1] * n
    
    dist[0] = 0
    que.append(0)

    while que:
        current = que.pop(0)
        
        for i in v[current]:
            i -= 1
            if dist[i] != -1 :continue
            dist[i] = dist[current] + 1
            que.append(i)
    
    return dist

dist = bfs(0)
for i,dis in enumerate(dist):
    print(i+1,dis)

コメント

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