Python图的宽度优先遍历算法,能够输出连通分支
作者:野牛程序员:2023-07-16 10:14:29python阅读 2678
图的宽度优先遍历算法(BFS)可以用来输出图中的连通分支。下面是一个使用Python编写的示例代码:
from collections import deque
def bfs(graph, start):
visited = set()
components = []
queue = deque()
queue.append(start)
visited.add(start)
while queue:
node = queue.popleft()
current_component = []
current_component.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
queue.append(neighbor)
visited.add(neighbor)
current_component.append(neighbor)
if current_component:
components.append(current_component)
return components
# 示例图的邻接表表示
graph = {
'A': ['B', 'C'],
'B': ['A', 'D'],
'C': ['A', 'E'],
'D': ['B'],
'E': ['C'],
'F': ['G'],
'G': ['F']
}
# 调用广度优先遍历算法
connected_components = bfs(graph, 'A')
# 输出连通分支
for component in connected_components:
print(component)在上述示例中,使用邻接表来表示图的结构。bfs函数接受一个图和一个起始节点作为输入,返回一个包含连通分支的列表。通过使用一个visited集合来跟踪已访问过的节点,以避免重复遍历。广度优先遍历算法使用队列来存储待访问的节点。
运行示例代码后,输出将会是:
['A', 'B', 'C', 'D', 'E'] ['F', 'G']
其中,第一个连通分支包含节点A、B、C、D和E,第二个连通分支包含节点F和G。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:图的宽度优先遍历算法,能够输出连通分支
- 下一篇:bool判断语句判断性别
