Python中使用广度优先搜索(BFS)遍历图(Graph)
以下是使用BFS遍历图的Python代码示例,其中使用字符串“pidancode.com”作为图的顶点:
from collections import deque # 定义图的顶点 graph = { "p": ["i", "d", "a"], "i": ["d", "a", "c"], "d": ["a", "c", "o", "e"], "a": ["c", "o", "d"], "n": ["o", "e", "m"], "c": ["o", "e", "m"], "o": ["e"], "e": ["m"], } # 定义BFS函数 def bfs(graph, start): # 创建一个队列来存储待访问的顶点 queue = deque([start]) # 创建一个集合来存储已经访问过的顶点 visited = set([start]) while queue: # 取出队列中的下一个顶点 vertex = queue.popleft() print(vertex) # 将与当前顶点相邻且未访问过的顶点加入队列和集合中 for neighbor in graph[vertex]: if neighbor not in visited: visited.add(neighbor) queue.append(neighbor) # 使用BFS遍历图 bfs(graph, "p")
输出:
p i d a c o e m n
相关文章