python最小生成树算法代码,返回存放最小生成树边的列表
时间: 2023-10-04 09:05:01 浏览: 90
下面是使用Prim算法实现的Python代码,返回最小生成树边的列表:
```python
def prim(graph):
"""
:param graph: 二维数组表示的图
:return: 最小生成树边的列表
"""
n = len(graph)
# 初始化距离数组
dist = [float('inf')] * n
# 初始化父节点数组
parent = [-1] * n
# 选取第一个节点作为起点
dist[0] = 0
# 记录已经加入最小生成树的节点
mst_set = set()
while len(mst_set) < n:
# 选取距离最小的节点
u = dist.index(min(dist))
# 将该节点加入最小生成树
mst_set.add(u)
# 更新与该节点相邻的节点的距离和父节点
for v in range(n):
if graph[u][v] != 0 and v not in mst_set and graph[u][v] < dist[v]:
dist[v] = graph[u][v]
parent[v] = u
# 构建最小生成树边的列表
edges = []
for i in range(1, n):
edges.append((parent[i], i))
return edges
```
其中,`graph`是一个二维数组,表示图的邻接矩阵。返回的是一个元组列表,每个元组表示一条边,其中第一个元素是起点,第二个元素是终点。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)