AcWing 847. 图中点的层次-python
原题链接
简单
作者:
Actor丶
,
2020-02-14 13:49:51
,
所有人可见
,
阅读 1392
def bfs():
# 1. 初始化队列和状态
queue = [1]
# 2. while queue不为空
while queue:
# 3. 队顶元素出队
t = queue.pop(0)
if t not in graph: continue # !!!注意:判断如果元素t不存在相邻节点(即出度为0),则跳过
# 4. 遍历,满足条件的节点入队
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])
# 1. 输入示例
n, m = map(int, input().split())
# 2. 图的存储模板(有向图)
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)
# 3.初始化状态
st = [False for i in range(n+1)]
st[1] = True
d = [-1 for i in range(n+1)] # 用来存储每个点到节点1的距离
d[1] = 0
# 4. bfs搜索
bfs()