コード例 #1
0
        // The presented code is based on the implementation shown at:
        // https://www.geeksforgeeks.org/greedy-algorithms-set-2-kruskals-minimum-spanning-tree-mst/
        public List <Edge <T> > MinimumSpanningTreeKruskal()
        {
            List <Edge <T> > edges = GetEdges();

            edges.Sort((a, b) => a.Weight.CompareTo(b.Weight));
            Queue <Edge <T> > queue = new Queue <Edge <T> >(edges);

            Subset <T>[] subsets = new Subset <T> [Nodes.Count];
            for (int i = 0; i < Nodes.Count; i++)
            {
                subsets[i] = new Subset <T>()
                {
                    Parent = Nodes[i]
                };
            }

            List <Edge <T> > result = new List <Edge <T> >();

            while (result.Count < Nodes.Count - 1)
            {
                Edge <T> edge = queue.Dequeue();
                Node <T> from = GetRoot(subsets, edge.From);
                Node <T> to   = GetRoot(subsets, edge.To);
                if (from != to)
                {
                    result.Add(edge);
                    Union(subsets, from, to);
                }
            }

            return(result);
        }
コード例 #2
0
 public UnionFind(int V)
 {
     subsets = new Subset[V];
     for (int i = 0; i < V; i++)
     {
         subsets[i]        = new Subset();
         subsets[i].Parent = i;
         subsets[i].Rank   = 0;
     }
 }
コード例 #3
0
        public List <Edge> Kruskal(WebGraph _graph)
        {
            int verticesCount = _graph.nodes.Count;

            Edge[] result = new Edge[verticesCount];
            Edge[] edges  = _graph.edges.ToArray();
            int    i      = 0;
            int    e      = 0;

            Array.Sort(edges, delegate(Edge a, Edge b)
            {
                return(a.value.CompareTo(b.value));
            });

            Subset[] subsets = new Subset[verticesCount];

            for (int v = 0; v < verticesCount; ++v)
            {
                subsets[v].Parent = v;
                subsets[v].Rank   = 0;
            }

            while (e < verticesCount - 1)
            {
                Edge nextEdge = edges[i++];
                int  x        = Find(subsets, nextEdge.to);
                int  y        = Find(subsets, nextEdge.from);

                if (x != y)
                {
                    result[e++] = nextEdge;
                    Union(subsets, x, y);
                }
            }
            List <Edge> Edges = new List <Edge>(result);

            Edges.RemoveAt(Edges.Count - 1);
            return(Edges);
        }