FindMinimumSpanningTree(WeightedGraph <T, TW> graph)
        {
            var edges = new List <MSTEdge <T, TW> >();


            //gather all unique edges
            dfs(graph.ReferenceVertex, new System.Collections.Generic.HashSet <T>(),
                new Dictionary <T, System.Collections.Generic.HashSet <T> >(),
                edges);

            //quick sort preparation
            var sortArray = new MSTEdge <T, TW> [edges.Count];

            for (int i = 0; i < edges.Count; i++)
            {
                sortArray[i] = edges[i];
            }

            //quick sort edges
            var sortedEdges = MergeSort <MSTEdge <T, TW> > .Sort(sortArray);

            var result      = new List <MSTEdge <T, TW> >();
            var disJointSet = new DisJointSet <T>();

            //create set
            foreach (var vertex in graph.Vertices)
            {
                disJointSet.MakeSet(vertex.Key);
            }


            //pick each edge one by one
            //if both source & target belongs to same set
            //then don't add the edge to result
            //otherwise add it to result and union sets
            for (int i = 0; i < edges.Count; i++)
            {
                var currentEdge = sortedEdges[i];

                var setA = disJointSet.FindSet(currentEdge.Source);
                var setB = disJointSet.FindSet(currentEdge.Destination);

                //can't pick edge with both ends already in MST
                if (setA.Equals(setB))
                {
                    continue;
                }

                result.Add(currentEdge);

                //union picked edge vertice sets
                disJointSet.Union(setA, setB);
            }

            return(result);
        }
示例#2
0
 public int CompareTo(MSTEdge <T, W> other)
 {
     return(Weight.CompareTo(other.Weight));
 }