Ejemplo n.º 1
0
        private readonly Collections.Queue <EdgeW> _mst = new Collections.Queue <EdgeW>(); // edges in MST

        /// <summary>
        /// Compute a minimum spanning tree (or forest) of an edge-weighted graph.
        /// </summary>
        /// <param name="g">g the edge-weighted graph</param>
        public KruskalMST(EdgeWeightedGraph g)
        {
            // more efficient to build heap by passing array of edges
            var pq = new MinPQ <EdgeW>();

            foreach (var e in g.Edges())
            {
                pq.Insert(e);
            }

            // run greedy algorithm
            var uf = new UF(g.V);

            while (!pq.IsEmpty() && _mst.Size() < g.V - 1)
            {
                var e = pq.DelMin();
                var v = e.Either();
                var w = e.Other(v);
                if (!uf.Connected(v, w))
                {                    // v-w does not create a cycle
                    uf.Union(v, w);  // merge v and w components
                    _mst.Enqueue(e); // add edge e to mst
                    _weight += e.Weight;
                }
            }

            // check optimality conditions
            //assert check(G);
        }