-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implemented dijsktra to return shortest odom path
- Loading branch information
1 parent
a8e483b
commit 182519a
Showing
3 changed files
with
80 additions
and
4 deletions.
There are no files selected for viewing
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
def dijsktra(graph, initial, end): | ||
# shortest paths is a dict of nodes | ||
# whose value is a tuple of (previous node, weight) | ||
shortest_paths = {initial: (None, 0)} | ||
current_node = initial | ||
visited = set() | ||
|
||
while current_node != end: | ||
visited.add(current_node) | ||
destinations = graph.edges[current_node] | ||
weight_to_current_node = shortest_paths[current_node][1] | ||
|
||
for next_node in destinations: | ||
weight = graph.weights[(current_node, next_node)] + weight_to_current_node | ||
if next_node not in shortest_paths: | ||
shortest_paths[next_node] = (current_node, weight) | ||
else: | ||
current_shortest_weight = shortest_paths[next_node][1] | ||
if current_shortest_weight > weight: | ||
shortest_paths[next_node] = (current_node, weight) | ||
|
||
next_destinations = {node: shortest_paths[node] for node in shortest_paths if node not in visited} | ||
if not next_destinations: | ||
return [] #if no path possible, return empty list | ||
|
||
# next node is the destination with the lowest weight | ||
current_node = min(next_destinations, key=lambda k: next_destinations[k][1]) | ||
|
||
# Work back through destinations in shortest path | ||
path = [] | ||
while current_node is not None: | ||
path.append(current_node) | ||
next_node = shortest_paths[current_node][0] | ||
current_node = next_node | ||
# Reverse path | ||
path = path[::-1] | ||
return path | ||
|