用Java实现的最小生成树的普里姆算法

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

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值