AcWing 847. 图中点的层次 python
原题链接
简单
作者:
申侠
,
2020-10-21 21:22:33
,
所有人可见
,
阅读 236
from queue import Queue
class graph(object):
def __init__(self, n=None, N=200010):
self.h = [-1] * N
self.e = [-1] * N
self.ne = [-1] * N
self.n = n
self.idx = 0
self.st = [False] *N
def add(self, a, b):
idx = self.idx
self.e[idx] = b
self.ne[idx] = self.h[a]
self.h[a] = idx
self.idx += 1
def bfs(self, u, t):
q = Queue()
q.put([u,0])
while not q.empty():
p, lvl = q.get()
self.st[p] = True
i = self.h[p]
while i != -1:
v = self.e[i]
if v == t:
return lvl + 1
if not self.st[v]:
q.put([v, lvl+1])
i = self.ne[i]
return -1
n, m = map(int, input().split(' '))
g = graph()
for _ in range(m):
a, b = map(int, input().split(' '))
g.add(a, b)
print(g.bfs(1, n))