Dijkstra algorithm for finding the shortest paths from the given node to all other nodes. Returns a dictionary of node id's, each linking to a list of node id's (i.e., the path).
(graph, id, heuristic=None, directed=False)
| 808 | heappush(q, (cost1 + cost2, n2, path)) |
| 809 | |
| 810 | def dijkstra_shortest_paths(graph, id, heuristic=None, directed=False): |
| 811 | """ Dijkstra algorithm for finding the shortest paths from the given node to all other nodes. |
| 812 | Returns a dictionary of node id's, each linking to a list of node id's (i.e., the path). |
| 813 | """ |
| 814 | # Based on: Dijkstra's algorithm for shortest paths modified from Eppstein. |
| 815 | # Based on: NetworkX 1.4.1: Aric Hagberg, Dan Schult and Pieter Swart. |
| 816 | # This is 5x faster than: |
| 817 | # for n in g: dijkstra_shortest_path(g, id, n.id) |
| 818 | W = adjacency(graph, directed=directed, heuristic=heuristic) |
| 819 | Q = [] # Use Q as a heap with (distance, node id)-tuples. |
| 820 | D = {} # Dictionary of final distances. |
| 821 | P = {} # Dictionary of paths. |
| 822 | P[id] = [id] |
| 823 | seen = {id: 0} |
| 824 | heappush(Q, (0, id)) |
| 825 | while Q: |
| 826 | (dist, v) = heappop(Q) |
| 827 | if v in D: continue |
| 828 | D[v] = dist |
| 829 | for w in W[v].iterkeys(): |
| 830 | vw_dist = D[v] + W[v][w] |
| 831 | if w not in D and (w not in seen or vw_dist < seen[w]): |
| 832 | seen[w] = vw_dist |
| 833 | heappush(Q, (vw_dist, w)) |
| 834 | P[w] = P[v] + [w] |
| 835 | for n in graph: |
| 836 | if n not in P: P[n]=None |
| 837 | return P |
| 838 | |
| 839 | def floyd_warshall_all_pairs_distance(graph, heuristic=None, directed=False): |
| 840 | """ Floyd-Warshall's algorithm for finding the path length for all pairs for nodes. |
no test coverage detected
searching dependent graphs…