编程利用广度优先搜索算法确定无向图的的连通分量python
时间: 2023-06-16 17:02:00 浏览: 97
下面是利用广度优先搜索算法确定无向图连通分量的 Python 代码实现:
```python
from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
while queue:
vertex = queue.popleft()
if vertex not in visited:
visited.add(vertex)
queue.extend(graph[vertex] - visited)
return visited
def connected_components(graph):
visited = set()
components = []
for vertex in graph:
if vertex not in visited:
component = bfs(graph, vertex)
visited.update(component)
components.append(component)
return components
```
其中,`graph` 是一个字典,表示无向图的邻接表。字典的键是图中的节点,值是一个集合,表示该节点所连接的其他节点。
例如,对于如下无向图:
```
1---2---3
\ / \ /
4---5
```
邻接表为:
```python
graph = {
1: {2, 4},
2: {1, 3, 4, 5},
3: {2, 5},
4: {1, 2, 5},
5: {2, 3, 4}
}
```
可以调用 `connected_components(graph)` 函数来获取该无向图的连通分量。
示例输出:
```
[{1, 2, 3, 4, 5}]
```
阅读全文