1

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?

kklaw
  • 452
  • 2
  • 4
  • 14
  • Does this answer your question? [Dijkstra's algorithm in python](https://stackoverflow.com/questions/22897209/dijkstras-algorithm-in-python) – sehan2 Jul 12 '21 at 19:04

1 Answers1

0

hope it will work

def solve(graph,visited,a,b): #a start vertex, b end vertex
    dist={}
    for node in visited:
        dist[node]=float("inf")
    dist[a]=0
    d=graph.copy()
    while d:
        mn=None
        for node in d: # finding closest vertex
            if not mn:
                mn=node
            elif dist[node]<dist[mn]:
                mn=node
        for child,cost in graph[mn].items(): #updating distance 
            if dist[mn]+cost<dist[child]:
                dist[child]=dist[mn]+cost
        d.pop(mn) # removing mn as we updated distance wrt this vertex
    return dist
 
n = int(input()) #number of vertices
graph = {}
visited={}
for i in range(n):
    u=input()
    graph[u]={}
    visited[u]=0
e = int(input())
for i in range(e):
    u, v, t = map(str, input().split()) # t is cost(must be positive)
    graph[u][v]=int(t)
a = input()
b = input()
print(solve(graph,visited, a, b))