文章目錄
Prim算法(java)
設N=(V, E)是連通網,T=(U,E1)是正在構造的生成樹。剛開始。這棵樹只有一個頂點,沒有邊(假設從1開始)U={1}, E1={}。在所有u屬於U,v屬於V-U中,選一條代價最小的邊(u,v)併入T中,U={1,3}, E1={(1,3)},依次執行,直到V=U爲止,即得到最小生成樹T
如下圖,先從1開始選擇鄰近最小的3,然後選擇6···依次比較下去
需要注意的是下一條邊是已選擇的點與未選擇的點之間連接的最小代價的邊
輸入
6 10
1 2 6
1 3 1
1 4 5
2 3 5
2 5 3
3 4 5
3 5 6
3 6 4
4 6 2
5 6 6
輸出
closest[3]=1
closest[6]=3
closest[4]=6
closest[2]=3
closest[5]=2
下面貼上代碼
import java.util.Arrays;
import java.util.Scanner;
public class prim {
public static void main(String args[ ]){
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
int[][] cost = new int[n+1][n+1];
for(int i = 1; i<n+1; i++){
Arrays.fill(cost[i], Integer.MAX_VALUE);
}
for(int i = 0; i<m; i++){
int x = scanner.nextInt();
int y = scanner.nextInt();
int p = scanner.nextInt();
cost[x][y] = cost[y][x] = p;
}
prim(cost, n, Integer.MAX_VALUE);
}
public static void prim(int[][] cost, int n, int maxi){
int lowcost[] = new int[n+1];
int closest[] = new int[n+1];
for(int i = 2; i<n+1; i++){
lowcost[i] = cost[1][i];
closest[i] = 1;
}
int min, m;
//尋找鄰近最小路徑
for(int i = 2; i<n+1; i++){
min = maxi;
m = 1;
for(int j = 2; j<n+1; j++){
if(lowcost[j] < min && lowcost[j] != 0){
m = j;
min = lowcost[j];
}
}
//輸出生成樹的邊
System.out.println("closest[" + m + "]=" + closest[m]);
lowcost[m] = 0;
closest[m] = 0;
//調整代價
for(int j = 2; j<n+1; j++){
if(cost[m][j] < lowcost[j] && cost[m][j] != 0){
lowcost[j] = cost[m][j];
closest[j] = m;
}
}
}
}
}