最小代价数(最小生成树) Krushal算法

package graph.basic;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class G_MinTree_Krushal {

	/**
	 * 
	 *    无向图 最小代价数(最小生成树)  Krushal  克鲁斯卡算法
	 *    关键点1: 每次选择最小的边
	 *    2.确定选择该边后不会构成回路,判定是否构成回路的方法是建立一个标记数组,标记各点所在的连通区域
	 *    并在每次选择边后,实时更新标记数组
	 */
	private List G_edge = new ArrayList();
	private List minTreeEdge = new ArrayList();
	private int vertexNum;

	G_MinTree_Krushal(int vertexNum) {
		this.vertexNum = vertexNum;
	}

	class Edge {
		int vertex1;
		int vertex2;
		int weight;
		Edge(int v1, int v2, int weight) {
			this.vertex1 = v1;
			this.vertex2 = v2;
			this.weight = weight;
		}
	}

	@SuppressWarnings("unchecked")
	public void addEdge(int vertex1, int vertex2, int weight) {
		Edge newEdge = new Edge(vertex1, vertex2, weight);
		G_edge.add(newEdge);
	}

	@SuppressWarnings("unchecked")
	public void krushal() {
		int[] area = new int[vertexNum + 1]; // 标记连通区域
		for (int i = 0; i < vertexNum; i++) {
			area[i] = i; // 初始化, 开始时每一个顶点就是一个连通区域
		}

		MyComparator myCom = new MyComparator();
		Collections.sort(G_edge, myCom);   //排序
		for (int i = 0; i < G_edge.size(); i++) {
			Edge e = (Edge) G_edge.get(i);
			int v1 = e.vertex1;
			int v2 = e.vertex2;
			if (area[v1] != area[v2]) { // 不在同一连通区域
				minTreeEdge.add(e);
				// 归并连通区域,
				int toChange = area[v2]; // 要改变的区域
				for (int j = 1; j < area.length; j++) {
					if (area[j] == toChange) {
						area[j] = area[v1];
					}
				}
			}

		}
		
		showMinTree();

	}

	public void showMinTree() {
		System.out.println("最小生成树的各边为:");
		for (int i = 0; i < minTreeEdge.size(); i++) {
			Edge e = (Edge) minTreeEdge.get(i);
			System.out.println("v" + e.vertex1 + "--->" + "v" + e.vertex2
					+ " weight:" + e.weight);

		}
	}

	class MyComparator implements Comparator {
		public int compare(Edge e1, Edge e2) {
			return e1.weight - e2.weight;
		}

	}

	public static void main(String[] args) {
		G_MinTree_Krushal g = new G_MinTree_Krushal(7);
		g.addEdge(1, 2, 17);
		g.addEdge(1, 5, 20);
		g.addEdge(1, 6, 4);
		g.addEdge(1, 7, 24);
		g.addEdge(2, 3, 6);
		g.addEdge(2, 4, 8);
		g.addEdge(2, 7, 12);
		g.addEdge(3, 4, 11);
		g.addEdge(4, 7, 15);
		g.addEdge(4, 5, 19);
		g.addEdge(5, 6, 9);
		g.addEdge(5, 7, 32);

		g.krushal();
	}

}


你可能感兴趣的:(数据结构)