public static void ShortestPaths(Graph graph, int vStart, IndexedPriorityQueue.IndexedPriorityQueue reachableNodes, out double[] pi, out int[] pred) { // idea: // greedy approach, // always extend a shortest path tree by the minimum reachable node // reachable nodes and shortest paths lengths are efficiently stored in a heap pi = new double[graph.Nodes()]; // shortest known path lengths pred = new int[graph.Nodes()]; // predeceesor nodes for these paths for (int v = 0; v < graph.Nodes(); v++) { pi[v] = System.Double.PositiveInfinity; pred[v] = -1; } pi[vStart] = 0.0; reachableNodes.Insert(vStart, pi[vStart]); while (!reachableNodes.Empty()) { int v = reachableNodes.DeleteMin(); // nearest reachable node List <Edge> edges = graph.Edges(v); for (int e = 0; e < edges.Count; e++) // test edges from v { int w = edges[e].To(); double weight = edges[e].Weight(); if (pi[w] > pi[v] + weight) // new vertex v leads to shorter path { pi[w] = pi[v] + weight; pred[w] = v; if (reachableNodes.Contains(w)) { reachableNodes.Change(w, pi[w]); } else { reachableNodes.Insert(w, pi[w]); } } } } }
public static void ShortestPathsArray(Graph graph, int vStart, out double[] pi, out int[] pred) { ShortestPaths(graph, vStart, new PriorityArray(graph.Nodes()), out pi, out pred); }