private void visit(EdgeWeightedGraph G, int v) { // Mark v and add to pq all edges from v to unmarked vertices. marked[v] = true; foreach (Edge e in G.Adj(v)) if (!marked[e.other(v)]) pq.Insert(e); }
private IndexPriorityQueue<Double> pq; // eligible crossing edges #endregion Fields #region Constructors public PrimMST(EdgeWeightedGraph G) { edgeTo = new Edge[G.V]; distTo = new double[G.V]; marked = new bool[G.V]; for (int v = 0; v < G.V; v++) distTo[v] = Double.PositiveInfinity; pq = new IndexPriorityQueue<double>(G.V); distTo[0] = 0.0; pq.Insert(0, 0.0); // Initialize pq with 0, weight 0. while (!pq.isEmpty()) visit(G, pq.Del()); // Add closest vertex to tree. }
static void Main(string[] args) { EdgeWeightedGraph ewg=new EdgeWeightedGraph(5); ewg.Filling(5); ewg.ShowEdges(); Console.WriteLine(); ewg.LazyPrimAlgr(); Console.WriteLine(); ewg.PrimAlgr(); Console.ReadKey(); }
private void visit(EdgeWeightedGraph G, int v) { // Add v to tree; update data structures. marked[v] = true; foreach (Edge e in G.Adj(v)) { int w = e.other(v); if (marked[w]) continue; // v-w is ineligible. if (e.Weight < distTo[w]) { // Edge e is new best connection from tree to w. edgeTo[w] = e; distTo[w] = e.Weight; if (pq.contains(w)) pq.change(w, distTo[w]); else pq.Insert(w, distTo[w]); } } }
private PriorityQueue<Edge> pq; // crossing (and ineligible) edges #endregion Fields #region Constructors public LazyPrimMST(EdgeWeightedGraph G) { pq = new PriorityQueue<Edge>(G.V); marked = new bool[G.V]; mst = new Queue<Edge>(); visit(G, 0); // assumes G is connected (see Exercise 4.3.22) while (!pq.isEmpty()) { Edge e = pq.Del(); // Get lowest-weight int v = e.either; int w = e.other(v); // edge from pq. if (marked[v] && marked[w]) continue; // Skip if ineligible. mst.Enqueue(e); // Add edge to tree. if (!marked[v]) visit(G, v); // Add vertex to tree if (!marked[w]) visit(G, w); // (either v or w). } }