private static AdjacencyListGraph <TWeight> ToAdjacencyGraph(int verticeCount, IEnumerable <Edge <TWeight> > edges, Action <AdjacencyListGraph <TWeight>, Edge <TWeight> > addEdge) { var graph = new AdjacencyListGraph <TWeight>(verticeCount); foreach (var edge in edges) { addEdge(graph, edge); } return(graph); }
private static PrimsResult PrimsAlgorithm(AdjacencyListGraph <decimal> graph) { var size = graph.Size(); //Initialize result with 0 as first vertex var result = new PrimsResult(size); result.Cost.SetValue(0, 0); //priority queue of costs var q = new MinPriorityQueue <decimal>(size, decimal.MaxValue); for (var i = 0; i < size; i++) { q.Enqueue(i, result.Cost.GetValue(i)); } //Walk while (!q.IsEmpty()) { //Console.WriteLine("Queue: {0}", q); var currentIndex = q.Dequeue(); //Console.WriteLine("Extract: {0}", currentIndex); foreach (var edge in graph.Neighbors(currentIndex)) { var z = edge.Right; var w = edge.Weight; if (!q.Contains(z) || result.Cost.GetValue(z) <= w) { continue; } result.Cost.SetValue(z, w); result.Parent.SetValue(z, currentIndex); q.ChangePriority(z, w); } } return(result); }