AOJ ALDS1_11_C Breadth First Search

備忘録

問題

http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_11_C&lang=ja

回答

import sys, os, math, bisect, itertools, collections, heapq, queue, copy, array

# from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall
# from decimal import Decimal
# from collections import defaultdict, deque

sys.setrecursionlimit(10000000)

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N = ii()
    visited = [-1] * N
    G = [[False] * N for _ in range(N)]
    for n in range(N):
        u, k, *V = il()
        for v in V:
            G[n][v - 1] = True

    que = queue.Queue()
    que.put(0)
    visited[0] = 0
    while not que.empty():
        now = que.get()
        for n in range(N):
            if G[now][n] and visited[n] == -1:
                visited[n] = visited[now] + 1
                que.put(n)

    for n in range(N):
        print(n + 1, visited[n])


if __name__ == '__main__':
    main()

考え方

螺旋本より、幅優先探索の入門問題。
与えられた有向グラフの頂点1から全ての頂点に対する最短距離を求める。

実装は、頂点1から移動可能な頂点をキューに入れて、
キューに入れられた頂点を次の移動開始地点とする。
注意点として、ある頂点の最短距離は、
今いる頂点までの最短距離 + 1とすること。
そのため、あらかじめ頂点1に対して、
最短距離を0としておく必要がある。
(頂点1は開始地点で移動が不要なため)