public Kruskal(WeightedGraph G) { var V = G.V(); var uf = new QuickUnion(V); var pq = new MinPQ <Edge>(); mst = new List <Edge>(); foreach (Edge e in G.edges()) { pq.Enqueue(e); } while (!pq.IsEmpty && mst.Count < V - 1) { var e = pq.DelMin(); var v = e.either(); var w = e.other(v); if (!uf.IsConnected(v, w)) { uf.Union(v, w); mst.Add(e); } } }
private void visit(WeightedGraph G, int v) { marked[v] = true; foreach (var e in G.adj(v)) { var w = e.other(v); if (!marked[w]) { pq.Enqueue(e); } } }
public void TestMinPQ() { MinPQ <int> pq = new MinPQ <int>(); for (var i = 0; i < 100; ++i) { pq.Enqueue(99 - i); } Assert.Equal(100, pq.Count); Assert.False(pq.IsEmpty); for (var i = 0; i < 100; ++i) { Assert.Equal(i, pq.DelMin()); Assert.Equal(99 - i, pq.Count); } Assert.True(pq.IsEmpty); }
public LazyPrim(WeightedGraph G) { var V = G.V(); marked = new bool[V]; pq = new MinPQ <Edge>(); var s = 0; foreach (var e in G.adj(s)) { pq.Enqueue(e); } mst = new List <Edge>(); while (!pq.IsEmpty && mst.Count < V - 1) { var e = pq.DelMin(); var v = e.either(); var w = e.other(v); if (marked[v] && marked[w]) { continue; } mst.Add(e); if (!marked[v]) { visit(G, v); } if (!marked[w]) { visit(G, w); } } }