summaryrefslogtreecommitdiffstats
path: root/algorithms.py
diff options
context:
space:
mode:
authorMax Bringemo <maxbr167@student.liu.se>2020-11-12 16:27:59 +0100
committerMax Bringemo <maxbr167@student.liu.se>2020-11-12 16:27:59 +0100
commit25fbaaef8f7e5bc261039fd9952d072676721f8f (patch)
treeadea85a0a826a226fbec9bc0d908b56838a8fa16 /algorithms.py
parentd429f09e7e3bc8173e765aba8a91f2440c99a324 (diff)
parent606c3eebe19114bcd2d07546a7c7d800ca84973f (diff)
downloadtdde25-25fbaaef8f7e5bc261039fd9952d072676721f8f.tar.gz
Merge branch 'dijkstra' into 'master'
Dijkstra See merge request tdde25-2020/tdde25-2020-projekt-sg3-maps-05!2
Diffstat (limited to 'algorithms.py')
-rw-r--r--algorithms.py34
1 files changed, 32 insertions, 2 deletions
diff --git a/algorithms.py b/algorithms.py
index cc8d35f..6e01287 100644
--- a/algorithms.py
+++ b/algorithms.py
@@ -1,3 +1,4 @@
+import heapq
import math
@@ -23,7 +24,7 @@ def get_closest_node_id(nodes, source_node):
for node_id, node in nodes.items():
length = length_haversine(source_node, node)
- if min_node == None or length < min_value:
+ if min_node is None or length < min_value:
min_node = node_id
min_value = length
@@ -32,4 +33,33 @@ def get_closest_node_id(nodes, source_node):
def find_shortest_path(nodes, source_id, target_id):
""" Return the shortest path using Dijkstra's algortihm. """
- return []
+ # queue contains multiple (walk_dist, (node_0, node_1, ... node_n))-tuples
+ # where (node_0, node_1, ... node_n) is a walk to node_n
+ # and walk_dist is the total length of the walk in meters
+ queue = [(0, (source_id,))]
+ visited = set()
+
+ while queue:
+ # consider an unchecked walk
+ walk_dist, walk = heapq.heappop(queue)
+ walk_end = walk[-1]
+ if walk_end == target_id:
+ # you have reached your destination
+ return walk
+ if walk_end in visited:
+ # there exists a shorter walk to walk_end
+ continue
+ # otherwise this is the shortest walk to walk_end
+ visited.add(walk_end)
+ # consider all our neighbours
+ for neighbour in nodes[walk_end].neighbours:
+ if neighbour in visited:
+ # there exists a shorter walk to neighbour
+ continue
+ # otherwise this MIGHT be the shortest walk to neighbour
+ # so put it in the queue
+ new_dist = walk_dist + length_haversine(nodes[walk_end], neighbour)
+ new_walk = walk + (neighbour.id,)
+ heapq.heappush(queue, (new_dist, new_walk))
+ # no path found
+ return None