public UndirectedGraph FindMinimumSpanningTree() { var tree = new UndirectedGraph(); var priorityQueue = new CustomPriotiryQueueForPrim(); var startNode = Vertices.Values.First(); startNode.Edges.ForEach(edge => priorityQueue.Push(edge)); tree.AddNode(startNode.Label); while (tree.Vertices.Count < Vertices.Count) { var minimumWeightEdge = priorityQueue.Pop(); var nextNode = minimumWeightEdge.To; if (tree.ContainsNode(nextNode.Label)) { continue; } tree.AddNode(nextNode.Label); tree.AddEdge(minimumWeightEdge.From.Label, nextNode.Label, minimumWeightEdge.Weight); nextNode.Edges.ForEach(edge => { if (!tree.ContainsNode(edge.To.Label)) { priorityQueue.Push(edge); } }); } return(tree); }
/// <summary> /// Recursive Implementation For Prim /// </summary> /// <param name="node"></param> /// <param name="spanningTree"></param> /// <param name="visited"></param> /// <param name="priotiryQueueForPrim"></param> /// <param name="path"></param> private void FindMinimumSpanningTree(Node node, UndirectedGraph spanningTree, HashSet <Node> visited, CustomPriotiryQueueForPrim priotiryQueueForPrim, Path path) { if (!visited.Contains(node)) { visited.Add(node); path.AddNode(node.Label); foreach (var edge in node.Edges) { priotiryQueueForPrim.Push(edge); } Edge edgeToVisit = null; while (edgeToVisit == null && priotiryQueueForPrim.Count() > 0) { var minimumPriorityEdge = priotiryQueueForPrim.Pop(); if (!visited.Contains(minimumPriorityEdge.To)) { edgeToVisit = minimumPriorityEdge; spanningTree.AddNode(edgeToVisit.From.Label); spanningTree.AddNode(edgeToVisit.To.Label); spanningTree.AddEdge(edgeToVisit.From.Label, edgeToVisit.To.Label, edgeToVisit.Weight); } } if (edgeToVisit != null) { FindMinimumSpanningTree(edgeToVisit.To, spanningTree, visited, priotiryQueueForPrim, path); } } }