Пример #1
0
        public EdgeDS[] KruskalMST()
        {
            // This will store the resultant MST
            EdgeDS[] mstEdges = new EdgeDS[myGraph.V - 1];
            for (int i = 0; i < myGraph.V - 1; i++)
            {
                mstEdges[0] = new EdgeDS();
            }

            // Step 1: Sort all the edges in non-decreasing order of their weight.
            // If we are not allowed to change the given graph, we can create a copy of array of edges.
            Array.Sort(myGraph.Edges);

            // Step 2: Allocate memory for creating V ssubsets
            SubsetDS[] subsets = new SubsetDS[myGraph.V];
            for (int i = 0; i < myGraph.V; i++)
            {
                subsets[i] = new SubsetDS(i, 0);
            }

            // Step 3: Number of Edges to be taken is V - 1
            int edgesCounter = 0;
            int nERequired   = 0;

            while (nERequired < myGraph.V - 1)
            {
                // Step 4: Pick the smallest edge. And increment the index for next iteration
                EdgeDS edge = new EdgeDS();
                edge = myGraph.Edges[edgesCounter++];

                int xRoot = myGraph.FindRoot(subsets, edge.Src);
                int yRoot = myGraph.FindRoot(subsets, edge.Dest);

                // Step 5: If including this edge does't cause cycle, include it in result and increment the index of result for next edge
                if (xRoot != yRoot)
                {
                    mstEdges[nERequired++] = edge;
                    myGraph.DoUnion(subsets, xRoot, yRoot);
                }
            }

            return(mstEdges);
        }
Пример #2
0
        public bool HasCycle()
        {
            SubsetDS[] subsets = new SubsetDS[this.V];
            for (int i = 0; i < this.V; i++)
            {
                subsets[i] = new SubsetDS(i, 0);
            }

            for (int i = 0; i < this.E; i++)
            {
                int xRoot = FindRoot(subsets, this.Edges[i].Src);
                int yRoot = FindRoot(subsets, this.Edges[i].Dest);
                if (xRoot == yRoot)
                {
                    return(true);
                }
                DoUnion(subsets, xRoot, yRoot);
            }

            return(false);
        }