普利姆算法(Prim)解决修路问题
普利姆算法应用当前问题得到的最小生成树思路图解:
java代码
package com
.bingym
.prim
;
import java
.util
.Arrays
;
public class PrimAlgorithm {
public static void main(String
[] args
) {
char[] data
= new char[]{'A','B','C','D','E','F','G'};
int verxNums
= data
.length
;
int [][]weight
=new int[][]{
{10000,5,7,10000,10000,10000,2},
{5,10000,10000,9,10000,10000,3},
{7,10000,10000,10000,8,10000,10000},
{10000,9,10000,10000,10000,4,10000},
{10000,10000,8,10000,10000,5,4},
{10000,10000,10000,4,5,10000,6},
{2,3,10000,10000,4,6,10000},};
Graph graph
= new Graph(verxNums
);
MinTree minTree
= new MinTree();
minTree
.createGraph(graph
,verxNums
,data
,weight
);
System
.out
.println("修路图的邻接矩阵为:");
minTree
.showGraph(graph
);
System
.out
.println("使得路的总里程数最少的路线为:");
minTree
.prim(graph
,0);
}
}
class MinTree {
public void createGraph(Graph graph
,int vertexNums
,char[] data
,int[][] weight
) {
int i
,j
;
for (i
= 0; i
< vertexNums
; i
++) {
graph
.data
[i
] = data
[i
];
for (j
= 0; j
< vertexNums
; j
++) {
graph
.weight
[i
][j
] = weight
[i
][j
];
}
}
}
public void showGraph(Graph graph
) {
for (int[] link
: graph
.weight
) {
System
.out
.println(Arrays
.toString(link
));
}
}
public void prim(Graph graph
,int start
) {
int[] visited
= new int[graph
.vertexNums
];
visited
[start
] = 1;
int vertex1
= -1;
int vertex2
= -1;
int minWeight
= 10000;
for (int k
= 1; k
< graph
.vertexNums
; k
++) {
for (int i
= 0; i
< graph
.vertexNums
; i
++) {
for (int j
= 0; j
< graph
.vertexNums
; j
++) {
if (visited
[i
] == 1 && visited
[j
] == 0 && graph
.weight
[i
][j
] < minWeight
) {
minWeight
= graph
.weight
[i
][j
];
vertex1
= i
;
vertex2
= j
;
}
}
}
System
.out
.println("边<" + graph
.data
[vertex1
] + "," + graph
.data
[vertex2
] + "> 权值:" + minWeight
);
visited
[vertex2
] = 1;
minWeight
= 10000;
}
}
}
class Graph {
int vertexNums
;
int[][] weight
;
char[] data
;
public Graph(int vertexNums
) {
this.vertexNums
= vertexNums
;
data
= new char[vertexNums
];
weight
= new int[vertexNums
][vertexNums
];
}
}
转载请注明原文地址:https://tech.qufami.com/read-19093.html