|
| 1 | +import heapq |
| 2 | + |
| 3 | +""" |
| 4 | +If we only want to find the shortest distance to the end and not all the nodes's shortest distance |
| 5 | +The ending condition will be when `end` pop out from the `pq`. |
| 6 | +And the path would be all the nodes that were popped out. |
| 7 | +""" |
| 8 | + |
| 9 | +#heap implementation |
| 10 | +def min_path(G, start, end): |
| 11 | + distance = {} |
| 12 | + pq = [] |
| 13 | + prev = {} |
| 14 | + path_str = '' |
| 15 | + visited = set() |
| 16 | + |
| 17 | + distance[start] = 0 |
| 18 | + heapq.heappush(pq, (0, start)) |
| 19 | + |
| 20 | + while pq: |
| 21 | + dis_to_mid, mid = heapq.heappop(pq) |
| 22 | + visited.add(mid) |
| 23 | + |
| 24 | + for dis, nei in G[mid]: |
| 25 | + if nei not in distance or distance[nei]>dis_to_mid+dis: |
| 26 | + distance[nei] = dis_to_mid+dis |
| 27 | + prev[nei] = mid |
| 28 | + if nei not in visited: |
| 29 | + heapq.heappush(pq, (distance[nei], nei)) |
| 30 | + |
| 31 | + curr = end |
| 32 | + while True: |
| 33 | + if curr not in prev: break |
| 34 | + path_str = ' -> '+prev[curr]+path_str |
| 35 | + curr = prev[curr] |
| 36 | + |
| 37 | + return path_str+' = '+str(distance[end]) |
| 38 | + |
| 39 | + |
| 40 | + |
| 41 | +#normal implementation |
| 42 | +def min_path(G, start, end): |
| 43 | + distance = {} #shortest distance from start |
| 44 | + prev = {} |
| 45 | + path_str = '' |
| 46 | + visited = set() |
| 47 | + |
| 48 | + distance[start] = 0 |
| 49 | + while True: |
| 50 | + #find nearest unvisited node |
| 51 | + mid = None |
| 52 | + dis_to_mid = float('inf') |
| 53 | + for node in distance: |
| 54 | + if node not in visited and distance[node]<dis_to_mid: |
| 55 | + mid = node |
| 56 | + dis_to_mid = distance[node] |
| 57 | + |
| 58 | + if mid==None: break |
| 59 | + visited.add(mid) |
| 60 | + |
| 61 | + #try to use mid to loosen the prev from start to mid's neighbors |
| 62 | + for dis, nei in G[mid]: |
| 63 | + if nei not in distance or dis_to_mid+dis<distance[nei]: |
| 64 | + distance[nei] = dis_to_mid+dis |
| 65 | + prev[nei] = mid |
| 66 | + |
| 67 | + curr = end |
| 68 | + while True: |
| 69 | + if curr not in prev: break |
| 70 | + path_str = ' -> '+prev[curr]+path_str |
| 71 | + curr = prev[curr] |
| 72 | + |
| 73 | + print path_str+' = '+str(distance[end]) |
| 74 | + |
| 75 | +G = { |
| 76 | + '0': [(1, '1'), (12, '2')], |
| 77 | + '1': [(9, '2'), (3, '3')], |
| 78 | + '2': [(5, '4')], |
| 79 | + '3': [(4, '2'), (13, '4'), (15, '5')], |
| 80 | + '4': [(4, '5')], |
| 81 | + '5': [] |
| 82 | +} |
| 83 | + |
| 84 | +print min_path(G, '0', '5') |
| 85 | + |
| 86 | + |
| 87 | + |
0 commit comments