背景
代码实现(Java)
package test01;
import java.util.Arrays;
public class primeAlgorithm {
public static void main(String args[]) {
char[] data = new char[] {'A','B','C','D','E','F','G'};
int[][] weight=new int[][] {
{100,5,7,100,100,100,2},
{5,100,100,9,100,100,3},
{7,100,100,100,8,100,100},
{100,9,100,100,100,4,100},
{100,100,8,100,100,5,4},
{100,100,100,4,5,100,6},
{2,3,100,100,4,6,100},
};
int verxs=data.length;
MGraph graph=new MGraph(verxs);
MinTree minTree=new MinTree();
minTree.creatGraph(graph, verxs, data, weight);
minTree.showGraph(graph);
minTree.prim(graph, 0);
}
}
class MinTree{
public void creatGraph(MGraph graph,int verxs,char data[],int[][] weight) {
int i,j;
for(i=0;i<verxs;i++) {
graph.data[i]=data[i];
for(j=0;j<verxs;j++) {
graph.weight[i][j]=weight[i][j];
}
}
}
public void showGraph(MGraph graph) {
for(int[] link:graph.weight) {
System.out.println(Arrays.toString(link));
}
}
public void prim(MGraph graph,int v) {
int visited[]=new int[graph.verxs];
visited[v]=1;
int h1 = -1;
int h2 = -1;
int minWeight = 10000;
for(int k=1;k<graph.verxs;k++) {
for(int i = 0;i<graph.verxs;i++) {
for(int j=0;j<graph.verxs;j++) {
if(visited[i]==1 && visited[j]==0 && graph.weight[i][j]<minWeight) {
minWeight = graph.weight[i][j];
h1=i;
h2=j;
}
}
}
System.out.println("边<"+graph.data[h1]+","+graph.data[h2]+">权值:"+minWeight);
visited[h2]=1;
minWeight=10000;
}
}
}
class MGraph{
int verxs;
char[] data;
int[][] weight;
public MGraph(int verxs) {
this.verxs=verxs;
data = new char[verxs];
weight = new int[verxs][verxs];
}
}