I have been trying to implement a Dijkstra-Algorithm with python:
def shortest_path(self, start, end):
pq = PriorityQueue()
pq.insert(0, start)
distances = {vertex: math.inf for vertex in range(self.graph.num_nodes)}
prev_nodes = {vertex: None for vertex in range(self.graph.num_nodes)}
visited = [False for vertex in range(self.graph.num_nodes)]
distances[start] = 0
prev_nodes[start] = start
while pq.size() > 0:
root = pq.get_min()
cur_distance = root.key
cur_vertex = root.value
pq.delete_min()
if cur_vertex == end:
break
if visited[cur_vertex] is False:
for neighbor, weight in self.graph.adj_matrix[cur_vertex]:
new_distance = cur_distance + weight
if new_distance < distances[neighbor]:
distances[neighbor] = new_distance
prev_nodes[neighbor] = cur_vertex
pq.insert(new_distance, neighbor)
visited[cur_vertex] = True
unfortunately it takes way too long for really long paths. Is there any way I could further optimize it?