这算法不好干讲,该说的都写到代码的注释里了,用命写的,且看且珍惜
package TanXing;
import java.util.Arrays;
public class myprim {
public static void main(String[] args) {
int sum = 0;
Prim();
System.out.println(Arrays.toString(iocs));
for(IOC ob : iocs){
sum += ob.weight;
}
System.out.println(sum);
}
//节点之间不可达标志
static int IM = 999;
//矩阵阶数
static int matrixnumber = 7;
//节点对数
static IOC []iocs = new IOC[matrixnumber - 1];
//矩阵
static int [][]area = {
{IM,23,IM,IM,IM,28,36},
{23,IM,20,IM,IM,IM,1},
{IM,20,IM,15,IM,IM,4},
{IM,IM,15,IM,3,IM,16},
{IM,IM,IM,3,IM,17,16},
{28,IM,IM,IM,17,IM,25},
{36,1,4,9,16,25,IM}
};
static void Prim(){
//初始化
for(int j = 0;j < iocs.length;j++){
iocs[j] = new IOC(0,j + 1,area[0][j+1]);
}
while (true){
if(Over()){
break;
}
else{
int minLengthNode = FindMinNode();
for(int i = 0;i < iocs.length;i++){
//看这一对节点所确定的边是否已是最小权值,如果不是,
// 就比较上一个最小节点和下一个边所确定的权值是否小于当前的权值
//如果是就执行以下步骤
//更新最小节点的下一个节点的权值
if(!iocs[i].prt && iocs[i].weight > area[minLengthNode][iocs[i].endNode]){
//把之前的起始节点改为
iocs[i].startNode = minLengthNode;
//把之前的权重改为现在的权重
iocs[i].weight = area[minLengthNode][iocs[i].endNode];
}
}
}
}
}
//给一个看是否已经遍历过节点对的方法
static boolean Over(){
for (int i = 0;i < iocs.length;i++){
if(!iocs[i].prt){
return false;
}
}
return true;
}
//找下一个最小节点
static int FindMinNode(){
int minWeight = 999;
int index = matrixnumber - 1;
for(int i = 0;i <iocs.length;i++){
if(!iocs[i].prt && iocs[i].weight < minWeight){
minWeight = iocs[i].weight;
index = i;
}
}
iocs[index].prt = true;
//指定下一个最小节点
int minNodeIndex = iocs[index].endNode;
return minNodeIndex;
}
}
//首先定义一个类去装一对节点和权重
class IOC{
//开始节点
public int startNode;
//结束节点
public int endNode;
//权重
public int weight;
//这对节点是否被遍历过
public boolean prt;
public IOC(int startNode, int endNode, int weight) {
this.startNode = startNode;
this.endNode = endNode;
this.weight = weight;
}
@Override
public String toString() {
return "IOC{" +
"startNode=" + startNode +
", endNode=" + endNode +
", weight=" + weight +
", prt=" + prt +
'}';
}
}
这算法花了我一下午的时间理解和掌握,哎!加油吧!