static void Main(string[] args) { var graph = new CustomWeightedGraph(); graph.AddNode("A"); graph.AddNode("B"); graph.AddNode("C"); graph.AddNode("D"); graph.AddEdge("A", "B", 3); graph.AddEdge("B", "C", 2); graph.AddEdge("B", "D", 4); graph.AddEdge("A", "C", 1); graph.AddEdge("C", "D", 5); graph.Print(); var from = "A"; var to = "D"; Console.WriteLine($"Shortest Distance {from}->{to} : {graph.GetShortestDistance(from, to)}"); Console.WriteLine($"Shortest Path {from}->{to}"); graph.GetShortestPath(from, to).Print(); Console.WriteLine($"Graph has cycle? : {graph.HasCycle()}"); Console.WriteLine("Creating Minimum Span Tree using Prim's Algorithm"); var minimumSpanTree = graph.MinimumSpanTree(); minimumSpanTree.Print(); }
public CustomWeightedGraph MinimumSpanTree() { // Prim's Algorithm var minSpanTree = new CustomWeightedGraph(); var totalNodes = GetTotalNodes(); var nodes = new HashSet <Node>(); var edgesPriorityQueue = new C5.IntervalHeap <Edge>(new EdgeComp()); if (itemsMap.Count == 0) { return(minSpanTree); // Error Handling } var node = itemsMap.Values.First(); // Randomly pick the first node to add to Minimum Span Tree nodes.Add(node); minSpanTree.AddNode(node.label); edgesPriorityQueue.AddAll(node.GetEdges()); while (nodes.Count < totalNodes) { var minEdge = edgesPriorityQueue.DeleteMax(); if (minSpanTree.ContainNode(minEdge.to.label) && minSpanTree.ContainNode(minEdge.from.label)) { continue; } node = minEdge.to; nodes.Add(node); minSpanTree.AddNode(node.label); minSpanTree.AddEdge(minEdge.from.label, minEdge.to.label, minEdge.weight); edgesPriorityQueue.AddAll(node.GetEdges().Where(e => !minSpanTree.ContainNode(e.to.label))); } return(minSpanTree); }