public Dijkstra(WeightSpareGraph <float> graph, int src) { Debug.Assert(src >= 0 && src < graph.V()); this.src = src; this.graph = graph; this.n = graph.V(); this.m = graph.E(); shortPath = new float[n]; book = new bool[n]; from = new int[n]; for (int i = 0; i != n; i++) { book [i] = false; from [i] = -1; //假设都是可达的 } from [src] = -1; shortPath [src] = 0f; IndexMinHeap <float> indexMinHeap = new IndexMinHeap <float> (n); indexMinHeap.Insert(src, shortPath[src]); while (indexMinHeap.Size() != 0) { int u = indexMinHeap.ExtraMinItemIndex(); book [u] = true; WeightSpareGraph <float> .adjIterator iter = new WeightSpareGraph <float> .adjIterator(graph, u); for (Edge <float> e = iter.begin(); !iter.isEnd(); e = iter.Next()) { int v = e.Other(u); if (!book[v]) { if (from [v] == -1 || shortPath [v] > shortPath [u] + e.weight) { from [v] = u; shortPath [v] = shortPath [u] + e.weight; if (indexMinHeap.isContain(v)) { indexMinHeap.Change(v, shortPath [v]); } else { indexMinHeap.Insert(v, shortPath[v]); } } } } } }
public PrimMST(WeightSpareGraph <float> graph) { this.graph = graph; this.n = graph.V(); this.m = graph.E(); minSpanTreeValue = 0; book = new bool[n]; toEdgeArr = new List <Edge <float> >(); for (int i = 0; i != n; i++) { toEdgeArr.Add(null); } for (int i = 0; i != n; i++) { book [i] = false; } indexMinHeap = new IndexMinHeap <float> (m); book [0] = true; visit(0); while (indexMinHeap.Size() != 0) { int index = indexMinHeap.ExtraMinItemIndex(); Debug.Assert(toEdgeArr[index] != null); book[index] = true; visit(index); // int u = toEdgeArr [index].U (); // int v = toEdgeArr [index].V (); // if (book [u] && !book [v]) { // book [v] = true; // visit (v); // } else if(!book [u] && book [v]){ // book [u] = true; // visit (u); // } } for (int i = 1; i != n; i++) { minSpanTreeValue += toEdgeArr [i].weight; } }