AcWing 847. 图中点的层次-python
原题链接
简单
作者:
Actor丶
,
2020-02-14 13:49:51
,
所有人可见
,
阅读 1402
def bfs():
queue = [1]
while queue:
t = queue.pop(0)
if t not in graph: continue
for i in graph[t]:
if not st[i]:
st[i] = True
queue.append(i)
if d[i]==-1:
d[i] = d[t]+1
print(d[n])
n, m = map(int, input().split())
graph = {}
for i in range(m):
a,b = map(int, input().split())
if a not in graph:
graph[a] = [b]
else:
graph[a].append(b)
st = [False for i in range(n+1)]
st[1] = True
d = [-1 for i in range(n+1)]
d[1] = 0
bfs()