Ejemplo n.º 1
0
        public IEnumerable <Edge <TVertex> > Execute(TGraph graph)
        {
            if (graph == null)
            {
                throw new ArgumentNullException(nameof(graph));
            }
            if (_connectedComponentsCounter.Execute(graph) > 1)
            {
                throw new InvalidOperationException("For Kruskal's algorithm graph cannot contain more than one connected component");
            }

            var edges = graph.ReducedEdges;
            var sortedEdgeWeightEntries = graph.Weights.Where(w => edges.Contains(w.Key))
                                          .OrderBy(w => w.Value)
                                          .ToList();

            var graphCopy         = new UndirectedWeightedGraph <TVertex, int>(graph.Vertices) as TGraph;
            var spanningTreeEdges = new List <Edge <TVertex> >();

            foreach (var edgeWeightEntry in sortedEdgeWeightEntries)
            {
                var edge   = edgeWeightEntry.Key;
                var weight = edgeWeightEntry.Value;

                graphCopy.AddUndirectedEdge(edge.Source, edge.Destination, weight);

                if (IsAnyCycleDetected(graphCopy))
                {
                    graphCopy.RemoveUndirectedEdge(edge.Source, edge.Destination);
                }
                else
                {
                    spanningTreeEdges.Add(new Edge <TVertex>(edge.Source, edge.Destination));
                }
            }

            return(spanningTreeEdges);
        }