最小生成樹prim

Prim算法是一種用於在加權無向圖中找到最小生成樹的貪心算法。Prim算法從一個隨機選擇的頂點開始,每次選擇連線已選頂點和未選頂點集合中權值最小的邊,直到所有頂點都被包含在已選頂點集合中。Prim算法找到的最小生成樹包含所有頂點,且所有邊的權重之和最小。

以下是一個使用Python實現的Prim算法示例:

import sys # for max function

def prim(graph):
    num_vertices = len(graph)
    selected_vertices = [0] # Initialize the selected vertices list
    mst = [[0, -1, -1] for _ in range(num_vertices)]
    mst[0][0] = 0 # First vertex is always included in the MST

    for _ in range(num_vertices):
        min_key = sys.maxsize
        for i in range(num_vertices):
            if i in selected_vertices and mst[i][2] == -1: # If vertex is selected and not yet included in MST
                for j in range(num_vertices):
                    if j != i and graph[i][j] and mst[j][0] == -1: # If there is an edge between i and j and j is not yet included in MST
                        if mst[i][2] == -1 or graph[i][j][0] < min_key: # If there is a shorter path from i to j or vertex i has not been included in MST yet
                            min_key = graph[i][j][0] # Update min_key
                            mst[j][2] = graph[i][j][2]
                            mst[j][1] = i
        selected_vertices += list(mst)
        selected_vertices.remove(mst[num_vertices-1][1])
    return selected_vertices, mst[:num_vertices]

這段代碼中,graph是一個二維列表,表示圖的鄰接矩陣。每個元素graph[i][j]表示從頂點i到頂點j的邊的權重。最小生成樹的結果是一個列表,其中每個元素是一個三元組,表示一條邊的起點、終點和權重。在給定的無向圖中,每條邊的權重可能有兩個數字,通常這兩個數字分別是這條邊的兩個頂點,以表明這是一條邊的兩個部分。因此,上述代碼假設輸入圖的鄰接矩陣已按頂點進行排序。如果沒有這個假設,可能需要調整代碼來正確處理輸入數據。