import java.util.ArrayList;
public class PrimMiniSpanTree {
/**
* @param args
*/
protected final static int Max = 1000;
ArrayList<Closedge> al = new ArrayList<Closedge>();
public static void main(String[] args) {
PrimMiniSpanTree pm = new PrimMiniSpanTree();
int[][] m = { { Max, 6, 1, 5, Max, Max }, { 6, Max, 5, Max, 3, Max },
{ 1, 5, Max, 5, 6, 4 }, { 5, Max, 5, Max, Max, 2 },
{ Max, 3, 6, Max, Max, 6 }, { Max, Max, 4, 2, 6, Max } };
MGraph mg = new MGraph(m);
pm.prim(mg, 0);
}
public void prim(MGraph mg, int u) {
// Closedge[] closedges = new Closedge[6];
int k = u;
for (int j = 0; j < mg.getVertexNum(); j++)
{
Closedge cl = new Closedge();
cl.setVertex(u);
cl.setLowcost(mg.getCost(k, j));
al.add(j, cl);
// System.out.println(cl.getVertex()+","+cl.getLowcost());
}
// System.out.println("aaaaaaaaaaaaaaa");
for (int i = 0; i < mg.getVertexNum(); i++) {
k = min();
// System.out.println(k+"kkkkkkkkkkkkkkkkkk");
System.out.println("加入边权值:"+al.get(k).getLowcost() + "," +"加入顶点:"+ k);
al.get(k).setLowcost(0);
for (int j = 0; j < mg.getVertexNum(); j++)
if (mg.getCost(k, j) < al.get(j).getLowcost()&&mg.getCost(k, j)>0&&al.get(j).getLowcost()>0) {
al.get(j).setLowcost(mg.getCost(k, j));
// System.out.println(al.get(j).getLowcost()+"cccccccccccc");
al.get(j).setVertex(mg.getVertex(k));
// System.out.println(al.get(j).getVertex()+"eeeeeeeeee");
}
}
}
public int min() {
int m = Max;
int n = 0;
for (int i = 0; i < al.size(); i++) {
if (al.get(i).getLowcost() < m && al.get(i).getLowcost() > 0)
{
m = al.get(i).getLowcost();
n = i;
}
// System.out.println(al.get(i).getVertex()+","+al.get(i).getLowcost());
// System.out.println(m);
// System.out.println("ddddddddddddddddddd");
}
al.get(n).setLowcost(m);
al.get(n).setVertex(n);
return n;
}
}
package com.test.prim;
public class MGraph {
private int[] vertexs = new int[6]; //顶点集合
private int [][] matrix = new int[6][6];//矩阵
public MGraph(int [][] matrix)
{
for(int i = 0;i<matrix.length;i++)
{
for(int j = 0;j<matrix.length;j++)
{
this.matrix[i][j] = matrix[i][j];
}
}
for(int i=0;i<matrix.length;i++ )
{
vertexs[i] = i;
}
}
public int getVertexNum()
{
return matrix.length;
}
public int getCost(int vertex1,int vertex2)
{
return matrix[vertex1][vertex2];
}
public int getVertex(int i)
{
return vertexs[i];
}
}
package com.test.prim;
public class Closedge {
private int lowcost;
private int vertex;
public int getLowcost() {
return lowcost;
}
public void setLowcost(int lowcost) {
this.lowcost = lowcost;
}
public int getVertex() {
return vertex;
}
public void setVertex(int vertex) {
this.vertex = vertex;
}
}