-
Notifications
You must be signed in to change notification settings - Fork 0
/
dijkstras.py
36 lines (32 loc) · 1 KB
/
dijkstras.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from collections import defaultdict
import heapq as heap
def dijkstras(adjList, getDistance, points, source, destination):
visited = set()
parent = {source: source}
pQ = []
heap.heappush(pQ, (0, source))
g = defaultdict(lambda: float('inf')) # f() = g() (h(n) is 0, as there is no heuristic)
g[source] = 0
while pQ:
# greedy
_, node = heap.heappop(pQ)
if node == destination:
break
visited.add(node)
for successor in adjList[node]:
if successor not in visited:
if g[successor] > (new := g[node] + getDistance(points, node, successor)):
parent[successor] = node
g[successor] = new
heap.heappush(pQ, (new, successor))
path = []
current = destination
try: # sometimes parent[current] doesn't exist
while parent[current] != current: # this is only false for start node
path.append(current)
current = parent[current] # move up hierarchy
path.append(source)
except KeyError:
return -1
path.reverse()
return path