带权无向图Prim算法生成最小生成树
时间: 2025-01-05 22:36:00 浏览: 10
### 使用Prim算法构建最小生成树
#### 初始化阶段
对于给定的一个连通无向加权图 \(G = (V, E)\),其中\(V\)表示顶点集合,而\(E\)则代表边集。为了初始化Prim算法,选取任意一个起始节点作为根节点,并将其加入到已访问过的节点列表中。
#### 边的选择过程
在每一轮迭代过程中,从未被选中的边集中挑选一条连接已被纳入MST(Minimal Spanning Tree)部分的节点与其他未加入该结构的新节点之间的最短路径上的边[^1]。这条边应当满足两个条件:一是它的一端位于当前形成的MST内;二是另一端处于尚未处理的部分之中。通过这种方式逐步扩展直到所有的顶点都被包含进来为止。
#### 实现细节
下面是一个基于Python实现的简单版本:
```python
import sys
from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]
# A utility function to find the vertex with minimum distance value,
# from the set of vertices not yet included in shortest path tree.
def minKey(self, key, mstSet):
# Initialize min value
min_val = sys.maxsize
min_index = None
for v in range(self.V):
if key[v] < min_val and mstSet[v] == False:
min_val = key[v]
min_index = v
return min_index
def primMST(self):
key = [sys.maxsize] * self.V # Key values used to pick minimum weight edge in cut
parent = [None] * self.V # Array to store constructed MST
key[0] = 0 # Make key 0 so that this vertex is picked as first vertex
mstSet = [False] * self.V # To represent set of vertices not yet included in MST.
parent[0] = -1 # First node is always root of MST
for cout in range(self.V): # The following loop traverses other V-1 vertices
u = self.minKey(key, mstSet)
mstSet[u] = True # Add the picked vertex to the MST Set
# Update key value and parent index of the adjacent vertices of the picked vertex.
for v in range(self.V):
# graph[u][v] is non zero only for adjacent vertices of m
# mstSet[v] is false for vertices not yet included in MST
# Update the key only if graph[u][v] is smaller than key[v]
if ((self.graph[u][v] > 0) and
mstSet[v] == False and
key[v] > self.graph[u][v]):
key[v] = self.graph[u][v]
parent[v] = u
print ("Edge \tWeight")
for i in range(1, self.V):
print(parent[i], "-", i, "\t", self.graph[i][parent[i]])
```
此代码片段展示了如何利用邻接矩阵来存储图的信息并执行Prim算法以找到最小生成树。每次循环都会选出一个新的节点及其对应的最优边加入到正在增长的MST中去[^4]。
阅读全文