Beispiel #1
0
        /*-------------------Kruskal's Algorithm------------------------------*/

        public List <Edge <T> > MSTKruskal()
        {
            List <Edge <T> > edges = GetEdges();                    // get a list of edges

            edges.Sort((a, b) => a.Weight.CompareTo(b.Weight));     // sort ascending by weight
            Queue <Edge <T> > queue = new Queue <Edge <T> >(edges); // edges instances are queued in new queue

            Subset <T>[] subsets = new Subset <T> [Nodes.Count];    // Each node is added to it's own subset. subsets check if addition of edge causes creation of cycle
            for (int i = 0; i < Nodes.Count; i++)
            {
                subsets[i] = new Subset <T>()
                {
                    Parent = Nodes[i]
                };
            }

            List <Edge <T> > result = new List <Edge <T> >(); // store list of edges

            while (result.Count < Nodes.Count - 1)            // iterates until the correct number of edges found
            {
                Edge <T> edge = queue.Dequeue();              // get edge with min weight
                Node <T> from = GetRoot(subsets, edge.From);
                Node <T> to   = GetRoot(subsets, edge.To);
                if (from != to) // check if no other cycles were introduced
                {
                    result.Add(edge);
                    Union(subsets, from, to); // union two subsets
                }
            }
            return(result);
        }
Beispiel #2
0
        public static Graph KruskalSolve(Graph graph)
        {
            int verticesCount = graph.VerticesCount;

            Edge[] edgesArray = new Edge[verticesCount];

            Array.Sort(graph.Edges, (Edge a, Edge b) =>
            {
                return(a.Weight.CompareTo(b.Weight));
            });

            Subset[] subsets = new Subset[verticesCount];

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

            int e = default;
            int i = default;

            while (e < verticesCount - 1)
            {
                Edge nextEdge = graph.Edges[i++];
                int  x        = Find(subsets, nextEdge.Source);
                int  y        = Find(subsets, nextEdge.Destination);

                if (x != y)
                {
                    if (nextEdge != null)
                    {
                        edgesArray[e++] = nextEdge;
                    }
                    Union(subsets, x, y);
                }
            }

            return(new Graph
            {
                VerticesCount = verticesCount,
                Edges = edgesArray,
                EdgesCount = e,
            });
        }
    }