private KruskalMSTAlgorithm(EdgeWeightedGraph graph) { // It is more efficient to build a heap by passing array of edges. MinPQ <Edge> crossingEdgesByWeight = new MinPQ <Edge>(1); this._mst = new Queue <Edge>(); foreach (Edge edge in graph.GetEdges()) { crossingEdgesByWeight.Add(edge); } // Greedy algorithm UnionFinder uf = new UnionFinder(graph.VerticesCount); while (!crossingEdgesByWeight.IsEmpty && this._mst.Count < graph.VerticesCount - 1) { Edge edge = crossingEdgesByWeight.DeleteMin(); Int32 sourceVertice = edge.Source; Int32 targetVertice = edge.Target; if (!uf.IsConnected(sourceVertice, targetVertice)) { // sourceVertice - targetVertice does not create a cycle. uf.Union(sourceVertice, targetVertice); // Merge sourcerVertice and targetVertice components. this._mst.Enqueue(edge); // Add edge to minimum spanning tree. this.Weight += edge.Weight; } } }
public LazyPrimMST(EdgeWeightedGraph g) { _pq = new MinPQ <Edge>(g.E); _marked = new List <bool>(new bool[g.V]); _mst = new Queue <Edge>(); Visit(g, 0); while (!_pq.IsEmpty) { var e = (Edge)_pq.DeleteMin(); int v = e.Either(), w = e.Other(v); if (_marked[v] && _marked[w]) { continue; } _mst.Enqueue(e); if (!_marked[v]) { Visit(g, v); } if (!_marked[w]) { Visit(g, w); } } }
public void Test_Empty_WhenCleaning() { MinPQ <Int32> pq = new MinPQ <Int32>(1); pq.Add(2); pq.DeleteMin(); Assert.True(pq.IsEmpty); Assert.Equal(0, pq.Count); }
public void Test_AddDeleteMin_Order() { MinPQ <Int32> pq = new MinPQ <Int32>(10); for (int i = 1; i < 11; i++) { pq.Add(i); } for (int i = 1; i < 11; i++) { Assert.Equal(pq.DeleteMin(), i); } }
public KruskalMST(EdgeWeightedGraph g) { _mst = new Queue <Edge>(); var pq = new MinPQ <Edge>(g.E); foreach (var e in g.Edges()) { pq.Insert(e); } var uf = new UF(g.V); while (!pq.IsEmpty && _mst.Count < g.V - 1) { var e = (Edge)pq.DeleteMin(); int v = e.Either(), w = e.Other(v); if (uf.Connected(v, w)) { continue; } uf.Union(v, w); _mst.Enqueue(e); } }