public KruskalMST(WeightedUnDirectedGraph g)
        {
            this.G           = g;
            this.MSTEdges    = new Queue <WeightedUndirectedEdge>();
            this.TotalWeight = 0;

            minHeap = new MinHeap <WeightedUndirectedEdge>(this.G.GetVertices() * this.G.GetVertices());
            Uf      = new UnionFind(G.GetVertices());

            foreach (var vertex in G.GetVerticesList())
            {
                foreach (var edge in G.GetAdjacentEdges(vertex))
                {
                    minHeap.Insert(edge);
                }
            }

            while (!minHeap.IsEmpty())
            {
                WeightedUndirectedEdge edge = minHeap.ExtractMin();
                int u = edge.Either();
                int v = edge.Other(u);

                if (!Uf.Connected(u, v))
                {
                    MSTEdges.Enqueue(edge);
                    TotalWeight += edge.Weight();
                    Uf.Union(u, v);
                }
            }
        }
Esempio n. 2
0
        public PrimsMST(WeightedUnDirectedGraph g)
        {
            this.G           = g;
            this.MSTEdges    = new Queue <WeightedUndirectedEdge>();
            this.TotalWeight = 0;
            Visited          = new HashSet <int>();
            minHeap          = new MinHeap <WeightedUndirectedEdge>(this.G.GetVertices() * this.G.GetVertices());

            var vertex = G.GetVerticesList().ToList().First();

            this.Visit(vertex);

            while (!minHeap.IsEmpty())
            {
                WeightedUndirectedEdge edge = minHeap.ExtractMin();
                int u = edge.Either();
                int v = edge.Other(u);

                if (!Visited.Contains(u) || !Visited.Contains(v))
                {
                    MSTEdges.Enqueue(edge);
                    TotalWeight += edge.Weight();
                    var newVertex = Visited.Contains(u) ? v : u;
                    this.Visit(newVertex);
                }

                if (MSTEdges.Count >= G.GetVertices() - 1)
                {
                    break;
                }
            }
        }