(Shortest Path)
Dijkstra’s algorithm is a classic method for finding the shortest path from a starting node to every other node in a weighted graph (with non-negative edge weights).
dist
where every node’s distance is set to infinity (∞
), except the start node which is set to 0.previous
map to keep track of the best preceding node for each node (useful for reconstructing the shortest path).u
with the smallest distance from the queue.v
of u
:
alt = dist[u] + weight(u, v)
alt
is less than dist[v]
:
dist[v]
to alt
.previous[v]
to u
.v
in the priority queue with the new distance.dist
object contains the shortest distances from the start node to every other node.previous
map.Consider the following graph:
Goal: Find the shortest path from node A
to node D
.
dist = { A: 0, B: ∞, C: ∞, D: ∞ }
previous = {}
[(A, 0)]
alt = 0 + 1 = 1
→ Update dist[B] = 1
, previous[B] = A
.alt = 0 + 4 = 4
→ Update dist[C] = 4
, previous[C] = A
.[(B, 1), (C, 4)]
.alt = 1 + 2 = 3
→ Update dist[C] = 3
, previous[C] = B
.alt = 1 + 5 = 6
→ Update dist[D] = 6
, previous[D] = B
.[(C, 3), (C, 4), (D, 6)]
alt = 3 + 1 = 4
→ Update dist[D] = 4
, previous[D] = C
.[(D, 4), (D, 6)]
.previous[D] = C
previous[C] = B
previous[B] = A
https://drawtocode.vercel.app/problems/dijkstras-algorithm
Loading component...
Loading component...