2023-02-23 20:00:40 +08:00
|
|
|
|
"""
|
|
|
|
|
File: graph_bfs.py
|
|
|
|
|
Created Time: 2023-02-23
|
|
|
|
|
Author: Krahets (krahets@163.com)
|
|
|
|
|
"""
|
|
|
|
|
|
2023-10-19 16:21:51 +08:00
|
|
|
|
import sys
|
|
|
|
|
from pathlib import Path
|
2023-04-09 05:05:35 +08:00
|
|
|
|
|
2023-10-19 16:21:51 +08:00
|
|
|
|
sys.path.append(str(Path(__file__).parent.parent))
|
|
|
|
|
from modules import Vertex, vals_to_vets, vets_to_vals
|
2023-03-23 18:51:56 +08:00
|
|
|
|
from collections import deque
|
2023-02-23 20:00:40 +08:00
|
|
|
|
from graph_adjacency_list import GraphAdjList
|
|
|
|
|
|
2023-04-09 05:05:35 +08:00
|
|
|
|
|
2023-03-23 18:51:56 +08:00
|
|
|
|
def graph_bfs(graph: GraphAdjList, start_vet: Vertex) -> list[Vertex]:
|
2023-04-09 05:05:35 +08:00
|
|
|
|
"""广度优先遍历 BFS"""
|
2023-03-03 03:07:22 +08:00
|
|
|
|
# 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点
|
2023-02-23 20:00:40 +08:00
|
|
|
|
# 顶点遍历序列
|
|
|
|
|
res = []
|
|
|
|
|
# 哈希表,用于记录已被访问过的顶点
|
2023-03-23 18:51:56 +08:00
|
|
|
|
visited = set[Vertex]([start_vet])
|
2023-02-23 20:00:40 +08:00
|
|
|
|
# 队列用于实现 BFS
|
2023-03-23 18:51:56 +08:00
|
|
|
|
que = deque[Vertex]([start_vet])
|
2023-02-23 20:00:40 +08:00
|
|
|
|
# 以顶点 vet 为起点,循环直至访问完所有顶点
|
|
|
|
|
while len(que) > 0:
|
|
|
|
|
vet = que.popleft() # 队首顶点出队
|
2023-04-09 05:05:35 +08:00
|
|
|
|
res.append(vet) # 记录访问顶点
|
2023-02-23 20:00:40 +08:00
|
|
|
|
# 遍历该顶点的所有邻接顶点
|
|
|
|
|
for adj_vet in graph.adj_list[vet]:
|
|
|
|
|
if adj_vet in visited:
|
2023-04-09 05:05:35 +08:00
|
|
|
|
continue # 跳过已被访问过的顶点
|
2023-02-23 20:00:40 +08:00
|
|
|
|
que.append(adj_vet) # 只入队未访问的顶点
|
2023-04-09 05:05:35 +08:00
|
|
|
|
visited.add(adj_vet) # 标记该顶点已被访问
|
2023-02-23 20:00:40 +08:00
|
|
|
|
# 返回顶点遍历序列
|
|
|
|
|
return res
|
|
|
|
|
|
|
|
|
|
|
2023-04-09 05:30:02 +08:00
|
|
|
|
"""Driver Code"""
|
2023-02-23 20:00:40 +08:00
|
|
|
|
if __name__ == "__main__":
|
2023-04-09 05:05:35 +08:00
|
|
|
|
# 初始化无向图
|
2023-02-23 20:00:40 +08:00
|
|
|
|
v = vals_to_vets([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
|
2023-04-09 05:05:35 +08:00
|
|
|
|
edges = [
|
|
|
|
|
[v[0], v[1]],
|
|
|
|
|
[v[0], v[3]],
|
|
|
|
|
[v[1], v[2]],
|
|
|
|
|
[v[1], v[4]],
|
|
|
|
|
[v[2], v[5]],
|
|
|
|
|
[v[3], v[4]],
|
|
|
|
|
[v[3], v[6]],
|
|
|
|
|
[v[4], v[5]],
|
|
|
|
|
[v[4], v[7]],
|
|
|
|
|
[v[5], v[8]],
|
|
|
|
|
[v[6], v[7]],
|
|
|
|
|
[v[7], v[8]],
|
|
|
|
|
]
|
2023-02-23 20:00:40 +08:00
|
|
|
|
graph = GraphAdjList(edges)
|
|
|
|
|
print("\n初始化后,图为")
|
|
|
|
|
graph.print()
|
|
|
|
|
|
2023-04-09 05:05:35 +08:00
|
|
|
|
# 广度优先遍历 BFS
|
2023-02-23 20:00:40 +08:00
|
|
|
|
res = graph_bfs(graph, v[0])
|
|
|
|
|
print("\n广度优先遍历(BFS)顶点序列为")
|
2023-03-03 03:07:22 +08:00
|
|
|
|
print(vets_to_vals(res))
|