import java.util.Stack;
public class MinimumSpanningTree {
private MGraph mgraph = new MGraph();
public MinimumSpanningTree() {
}
public void createMST() {
Closedge[] closedge = new Closedge[MGraph.NODECOUNT + 1];
Stack<Integer> U = new Stack<Integer>();
// 先把编号为1的节点放入已联通集合
U.push(1);
int[][] edgeValue = this.mgraph.getEdgeValue();
for (int i = 2; i <= MGraph.NODECOUNT; i++) {
closedge[i] = new Closedge();
closedge[i].adjvex = 1;
closedge[i].lowcost = edgeValue[1][i];
// System.out.print(closedge[i].lowcost + " ");
}
System.out.println();
int minConnecEdge = 9999;
int nodeNum = 0;
while (U.size() < MGraph.NODECOUNT) {
minConnecEdge = 9999;
for (int i = 2; i <= MGraph.NODECOUNT; i++) {
closedge[i].lowcost = this.getMin(closedge[i].lowcost,
edgeValue[U.peek()][i]);
// System.out.print("i="+i+":"+closedge[i].lowcost + " ");
if (closedge[i].lowcost > 0
&& closedge[i].lowcost < minConnecEdge) {
minConnecEdge = closedge[i].lowcost;
nodeNum = i;
}
}
// System.out.println(nodeNum);
U.push(nodeNum);
closedge[nodeNum].lowcost = 0;
// System.out.println(U.size());
}
for (int i = 1; i <= MGraph.NODECOUNT; i++) {
System.out.println(U.pop());
}
}
private int getMin(int a, int b) {
return a < b ? a : b;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MinimumSpanningTree mst = new MinimumSpanningTree();
mst.createMST();
}
}
class Closedge {
int adjvex;
int lowcost;
}
public class MGraph {
public final static int NODECOUNT = 6;
// private int[][] graph = new int[NODECOUNT][NODECOUNT];
private int[][] edgeValue = { { 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 6, 1, 5, 9999, 9999 }, { 0, 6, 0, 5, 9999, 3, 9999 },
{ 0, 1, 5, 0, 5, 6, 4 }, { 0, 5, 9999, 5, 0, 9999, 2 },
{ 0, 9999, 3, 6, 9999, 0, 6 }, { 0, 9999, 9999, 4, 2, 6, 0 } };
public int[][] getEdgeValue() {
return edgeValue;
}
public void setEdgeValue(int[][] edgeValue) {
this.edgeValue = edgeValue;
}
//private int[][] minimumSpanningTree = new int[NODECOUNT + 1][NODECOUNT + 1];
public MGraph() {
}
@SuppressWarnings("unused")
private void connectNode() {
}
public void printMGraph() {
for (int i = 0; i < this.edgeValue[0].length; i++) {
for (int j = 0; j < this.edgeValue[0].length; j++) {
System.out.print(this.edgeValue[i][j] + " ");
}
System.out.println();
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MGraph mg = new MGraph();
mg.printMGraph();
}
}
用Java实现的最小生成树的普里姆算法
最新推荐文章于 2024-06-24 14:14:19 发布