示例#1
0
        public WeightedGraph GetMinimumSpanningTree()
        {
            var tree = new WeightedGraph();

            if (!nodes.Any())
            {
                return(tree);
            }

            var edges     = new PriorityQueue <Edge>();
            var startNode = nodes.FirstOrDefault().Value;

            foreach (var edge in startNode.GetEdges())
            {
                edges.Enqueue(edge);
            }
            tree.AddNode(startNode.Label);

            if (edges.Count() == 0)
            {
                return(tree);
            }

            while (tree.nodes.Count() < nodes.Count())
            {
                var minEdge  = edges.Dequeue();
                var nextNode = minEdge.To;

                if (tree.ContainsNode(nextNode.Label))
                {
                    continue;
                }

                tree.AddNode(nextNode.Label);
                tree.AddEdge(minEdge.From.Label, nextNode.Label, minEdge.Weight);

                foreach (var edge in nextNode.GetEdges())
                {
                    if (!tree.ContainsNode(edge.To.Label))
                    {
                        edges.Enqueue(edge);
                    }
                }
            }
            return(tree);
        }
        public WeightedGraph MinimumSpaningTree()
        {
            var tree = new WeightedGraph();

            var queue = new PriorityQueue <Edge, int>();

            var firstNode = Nodes.Values.First();

            foreach (var edge in firstNode.GetEdges())
            {
                queue.Enqueue(edge, edge.Weight);
            }

            tree.AddNode(firstNode.Label);



            while (tree.Nodes.Count < Nodes.Count && queue.Count != 0)
            {
                var minEdge  = queue.Dequeue();
                var nextNode = minEdge.To;

                if (tree.ContainsNode(nextNode.Label))
                {
                    continue;
                }

                tree.AddNode(nextNode.Label);
                tree.AddEdge(minEdge.From.Label, nextNode.Label, minEdge.Weight);

                foreach (var edge in nextNode.GetEdges())
                {
                    if (!tree.ContainsNode(edge.To.Label))
                    {
                        queue.Enqueue(edge, edge.Weight);
                    }
                }
            }

            return(tree);
        }