コード例 #1
0
        // 先判断有没有回路,有回路再处理
        public MSTEdge[] Kruskal()
        {
            // This will store the resultant MST
            MSTEdge[] mst = new MSTEdge[VertexCount - 1];
            // 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
            var sortedEdges = this.Edges.OrderBy(t => t.Weight);
            var enumerator  = sortedEdges.GetEnumerator();

            // Allocate memory for creating V ssubsets
            // Create V subsets with single elements
            MSTSubset[] subsets = new MSTSubset[VertexCount];
            for (int i = 0; i < subsets.Length; i++)
            {
                subsets[i]        = new MSTSubset();
                subsets[i].Parent = i;
                subsets[i].Rank   = 0;
            }
            // Number of edges to be taken is equal to V-1
            int e = 0;

            while (e < VertexCount - 1)
            {
                // Step 2: Pick the smallest edge. And increment the index
                // for next iteration
                MSTEdge nextEdge;
                if (enumerator.MoveNext())
                {
                    nextEdge = enumerator.Current;
                    int x = Find(subsets, nextEdge.Begin);
                    int y = Find(subsets, nextEdge.End);
                    // If including this edge does't cause cycle, include it
                    // in result and increment the index of result for next edge
                    if (x != y)
                    {
                        mst[e++] = nextEdge;
                        Union(subsets, x, y);
                    }
                    else
                    {
                        // Else discard the nextEdge
                    }
                }
            }
            return(mst);
        }
コード例 #2
0
 public bool HasCycle()
 {
     MSTSubset[] subsets = new MSTSubset[VertexCount];
     for (int i = 0; i < subsets.Length; i++)
     {
         subsets[i]        = new MSTSubset();
         subsets[i].Parent = i;
         subsets[i].Rank   = 0;
     }
     // Iterate through all edges of graph, find subset of both
     // vertices of every edge, if both subsets are same,
     // then there is cycle in graph.
     foreach (var edge in this.Edges)
     {
         int x = Find(subsets, edge.Begin);
         int y = Find(subsets, edge.End);
         if (x == y)
         {
             return(true);
         }
         Union(subsets, x, y);
     }
     return(false);
 }