AcWing 847. 图中点的层次 简单BFS
原题链接
简单
作者:
皓首不倦
,
2020-08-09 16:08:26
,
所有人可见
,
阅读 400
from collections import deque
n, m = map(int, input().split())
link = {i: set() for i in range(1, n+1)}
for _ in range(m):
a, b = map(int, input().split())
if a != b:
link[a].add(b)
def bfs():
que = deque()
que.append(1)
visit = [0] * (n+1)
visit[1] = 1
step = 0
while len(que) > 0:
node_num = len(que)
for _ in range(node_num):
cur = que.popleft()
if cur == n:
return step
for next in link[cur]:
if visit[next] == 0:
visit[next] = 1
que.append(next)
step += 1
return -1
print(bfs())