prim算法java语言实现

package com.test.prim;


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;
}

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值