图论-带权图的最小生成树(Prim)算法

算法设计:Prim算法从顶点开始着手。

从一个顶点开始,然后放入到树的集合中,然后重复做如下事情:

    (1)、找最新的顶点到其他顶点的所有边,这些顶点不能在树的集合中,把这些放入优先级队列。

    (2)、找到权值最小的边把它和它所到达的顶点放入树的集合中。

重复上述操作直到所有的顶点都在树中,程序结束。


Graph_mstw.java

package com.mapbar.structure;

/**
 * 
 * Class Graph_mstw.java
 * 
 * Description 带权图的最小生成树算法
 * 总原则:选择从已经处理过的点到未处理过的点的费用最低的边。
 * Company mapbar
 * 
 * author Chenll E-mail: 
 * 
 * Version 1.0
 * 
 * Date 2012-10-9 上午11:25:06
 */

// 定义边
class Edge {
	public int srcVert; // 源点

	public int destVert; // 目的点

	public int distance; // 距离

	public Edge(int sv, int dv, int d) {

		this.srcVert = sv;

		this.destVert = dv;

		this.distance = d;
	}
}

// 定义节点
class Vertex {
	public char label;

	public boolean isInTree;

	public Vertex(char l) {
		this.label = l;
		isInTree = false;
	}

}
//定义优先级队列,
//找到新的顶点到其它顶点所有边,这些顶点不能在树的集合中,放入优先级队列,找到费用最少的,把它和它所到达的顶点放入树的集合中
class PriorityQ{
	private final int SIZE = 20;
	private Edge[] queArray;
	private int size;
	
	public PriorityQ(){
		queArray = new Edge[SIZE];
		size = 0;
	}
	//新增
	public void insert(Edge item){
		int j;
		for(j = 0; j=queArray[j].distance){//从大到小排序
				break;
			}
		}
		//后移
		for(int i = size-1; i>=j; i--){
			queArray[i+1] = queArray[i];
		}
		queArray[j] = item;
		size ++;
	}
	
	//删除最小的
	public Edge removeMin(){
		return queArray[--size];
	}
	
	//删除第N个
	public void removeN(int n){
		//前移
		for(int i = n; i dis){ 
				thePQ.removeN(index);
				Edge theEdge = new Edge(currentVert,vertex,dis);
				thePQ.insert(theEdge);
			}
		} else {
			Edge theEdge = new Edge(currentVert,vertex,dis);
			thePQ.insert(theEdge);
		}
 	}
}

public class Graph_mstw {
	public static void main(String[] args){
		Graph g = new Graph();
		g.addVertex('A');
		g.addVertex('B');
		g.addVertex('C');
		g.addVertex('D');
		g.addVertex('E');
		g.addVertex('F');
		
		g.addEdge(0, 1, 6);
		g.addEdge(0, 3, 4);
		g.addEdge(1, 2, 10);
		g.addEdge(1, 3, 7);
		g.addEdge(1, 4, 7);
		g.addEdge(2, 3, 8);
		g.addEdge(2, 4, 5);
		g.addEdge(2, 5, 6);
		g.addEdge(3, 4, 12);
		g.addEdge(4, 5, 7);
		g.mstw();
	}
}

输出结果:AD AB BE EC CF 

你可能感兴趣的:(Data,Structure_JAVA,算法)