public LazyPrimMST(EdgeWeightedGraph g) { _pq = new MinPQ <Edge>(g.V() * g.V() / 2); _marked = new bool[g.V()]; _mst = new Queue <Edge>(); Visit(g, 0); while (_pq.Count > 0) { Edge e = _pq.DelMin(); int v = e.ThisVertex(); int w = e.OtherVertex(v); if (_marked[v] && _marked[w]) { continue; } _mst.Enqueue(e); if (!_marked[v]) { Visit(g, v); } if (!_marked[w]) { Visit(g, w); } } }
public KruskalMST(EdgeWeightedGraph g) { _uf = new PathCompressWeightedUnionFind(g.V()); _pq = new MinPQ <Edge>(g.V() * g.V()); _mst = new Queue <Edge>(); foreach (var e in g.Edges()) { _pq.Insert(e); } while (_pq.Count > 0 && _mst.Count < g.V() - 1) { Edge e = _pq.DelMin(); int v = e.ThisVertex(); int w = e.OtherVertex(v); if (_uf.Connected(v, w)) { continue; } _mst.Enqueue(e); _uf.Union(v, w); } }