最小生成樹python
最小生成樹 (Minimum Spanning Tree) 是一種常用的算法,它通過將給定圖中的所有頂點組合在一起,以最小化所有邊的總權重。在 Python 中,可以使用多種算法來實現最小生成樹,例如 Prim 算法和 Kruskal 算法。
以下是使用 Prim 算法實現最小生成樹的示例代碼:
import sys
def prim(graph, start):
# 初始化
num_vertices = len(graph)
selected_vertices = [start]
tree = []
mst_edges = []
for i in range(num_vertices):
tree.append([])
# 初始化邊列表
for i in range(num_vertices):
for j in range(i+1, num_vertices):
if graph[i][j] != sys.maxsize:
mst_edges.append((i, j, graph[i][j]))
while selected_vertices:
# 選擇最小的邊並將其添加到樹中
min_edge = min(mst_edges, key=lambda x: x[2])
i, j, weight = min_edge
tree[i].append(j)
selected_vertices.remove(j)
mst_edges.remove(min_edge)
# 更新權重最小的邊,如果這條邊連線的是已選擇的頂點,則更新其權重
for k in selected_vertices:
if graph[i][k] != sys.maxsize and graph[i][k] < weight:
weight = graph[i][k]
min_edge = (i, k, weight)
break
mst_edges.append(min_edge)
return tree, mst_edges
這段代碼使用了鄰接矩陣來表示圖,其中 graph[i][j]
表示頂點 i
和 j
之間的權重。代碼首先初始化一個空的樹和邊列表,並從給定的起始頂點開始進行遍歷。每次選擇一條權重最小的邊並將其添加到樹中,同時從已選擇的頂點列表中移除該頂點。當所有的頂點都被添加到樹中時,返回最小生成樹和邊的列表。
注意,此代碼需要適當的輸入和數據格式。在調用該函式時,您需要提供鄰接矩陣或頂點列表和起始頂點。例如:
graph = [[0, 2, 0, 6, 0],
[2, 0, 3, 8, 5],
[0, 3, 0, 0, 7],
[6, 8, 0, 0, 9],
[0, 5, 7, 9, 0]]
start = 0 # 選擇頂點 0 作為起始頂點
tree, mst_edges = prim(graph, start)