Dijkstra's Algorithm

Shortest path in weighted graphs using a greedy approach.

42158610
A
B
C
D
E
NodeABCDE
Min Dist0
Status: Ready

Algorithm Logic

1function dijkstra(start):
2 dist = {all: Infinity, start: 0}
3 pq = [(0, start)]
4
5 while pq:
6 curr_dist, curr = pq.pop_min()
7
8 if curr in visited: continue
9 visited.add(curr)
10
11 for neighbor, weight in adj[curr]:
12 new_dist = curr_dist + weight
13 if new_dist < dist[neighbor]:
14 dist[neighbor] = new_dist
15 pq.push((new_dist, neighbor))