Skip to content

Instantly share code, notes, and snippets.

@pedrohbtp
Created May 1, 2021 01:39
Show Gist options
  • Save pedrohbtp/7c3e57d4ba5c9d04014f47649275c4a7 to your computer and use it in GitHub Desktop.
Save pedrohbtp/7c3e57d4ba5c9d04014f47649275c4a7 to your computer and use it in GitHub Desktop.
import heapq
def dijkstra(cost_matrix, destination_node):
open_list = []
closed_list = set()
number_of_nodes = len(cost_matrix)
# (cum_cost, (previous_node, current_node))
heapq.heappush(open_list, (0, (0, 0)))
while open_list:
current_node = heapq.heappop(open_list)
# if the current node not already expanded
if current_node[1][1] not in closed_list:
closed_list.add(current_node[1][1])
if destination_node == current_node[1][1]:
return current_node
# expand
for next_node in range(number_of_nodes):
cost = cost_matrix[current_node[1][1]][next_node]
heapq.heappush(open_list, (cost+current_node[0], (current_node[1][1] ,next_node))) if next_node not in closed_list else None
return None
cost_matrix = [[ 0 ,20, 30, 100 ],
[ 20 ,0 ,15 ,75 ],
[ 30 ,15 ,0 ,50 ],
[ 100 ,75 ,50 ,0 ]]
dijkstra(cost_matrix, destination_node=3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment