How does Dijkstra's algorithm update distances step-by-step?
Dijkstra's algorithm updates distances by iteratively selecting the unvisited node with the smallest known distance, marking it as visited, and relaxing its outgoing edges. Relaxation involves checking if the path to a neighbor through the current node is shorter than the previously known path. If so, the neighbor's distance is updated.
Conditions
- Requires a priority queue or list to track unvisited nodes and their current shortest distances.
- The graph must have non-negative edge weights (positive in the pseudocode).
Reasoning, step by step
- Initialize distances: source = 0, others = infinity.
- Select the unvisited node with the smallest distance.
- For each neighbor of the selected node, calculate the tentative distance: dist(current) + weight(edge).
- If the tentative distance is less than the neighbor's current recorded distance, update the neighbor's distance and predecessor.
- Mark the selected node as visited.
- Repeat until all nodes are visited or the target is reached.
Example
In the video example, starting at A (dist 0), it updates B to 4 and C to 2. Then it selects C (dist 2), updating B to 3 (via C, since ), D to 6, and E to 7.
Common misconceptions
- Thinking that nodes are visited in alphabetical order or arbitrary order; they are visited in order of increasing shortest distance from the source.
- Assuming that once a distance is set, it never changes; distances are updated (relaxed) whenever a shorter path is found.
Watch the explanation
0:17 – 2:05Watch this moment ↗
Explore next
Answers are generated from source material and independently checked. Consult the original video or creator if something is unclear.