AcWing 847. 图中点的层次py
原题链接
简单
变量名都设置成 i, x, t, q, n 这种的可读性真的很差
coding style 负分
from collections import deque
def bfs(graph, d, n):
# 起点是1
queue = deque([1])
d[1] = 0
# bfs
while queue:
cur = queue.popleft()
# 确保cur有nxt
if cur in graph:
# 遍历所有的下一个next点
for nxt in graph[cur]:
if d[nxt] == -1:
d[nxt] = d[cur] + 1
queue.append(nxt)
# 目标点是n
print(d[n])
def main():
n, m = map(int, input().split())
# 图存储模板
graph = {}
for _ in range(m):
a, b = map(int, input().split())
if a not in graph:
graph[a] = [b]
else:
graph[a].append(b)
# d: distance d[1] - d[4] 4个点
d = [-1] * (n + 1)
bfs(graph, d, n)
main()