Home
DSA Visualizer
Data Structures
Dijkstra's Algorithm
Dijkstra's Algorithm
Dijkstra's algorithm finds the shortest path from a starting node to all other nodes in a weighted graph.
INIT
Priority queue
Shortest distance
Every distance starts at ∞ except A, which is 0. Push A.
Next
Pop A at distance 0 — the cheapest unsettled node, so 0 is final.
Source
Intuition
Imagine finding the quickest route on a map. You always take the road that gets you to a new town in the shortest total time.
Once you're sure you've found the fastest way to a town, you use that town to find fast routes to its neighbors.
Concept
- Greedy Approach: Always process the closest unvisited node next.
- Relaxation: If we find a path to node V through node U that is shorter than the current known path to V, we update (relax) the distance to V.
- Priority Queue: Used to efficiently select the node with the smallest tentative distance.
How it Works
- Set distance to start node = 0, all others = ∞.
- Add start node to a Priority Queue (PQ).
- While PQ is not empty:
- Pop node
uwith the smallest distance. - If
uis already visited, skip it. - Mark
uas visited. - For each neighbor
vofuwith weightw:- If
dist[u] + w < dist[v]: - Update
dist[v] = dist[u] + w. - Add
vto PQ.
- If
- Pop node
Step-by-Step Breakdown
Watch the visualization:
- Solid blue node: The node being settled: the smallest tentative distance left in the priority queue.
- Pale blue node with a blue outline: The neighbour being relaxed through it.
- Blue edge: The connection being checked for a shorter path.
- Green node: Settled: its shortest distance is final.
- Number above a node: Its current tentative distance from the start.
When to Use
Use Dijkstra's when:
- Finding optimal routes in GPS/Navigation systems.
- Routing data packets in networks (OSPF, IS-IS).
- The graph has non-negative edge weights.
When NOT to Use
- Negative Edge Weights: Dijkstra's can fail with negative weights. Use Bellman-Ford instead.
- Unweighted Graphs: BFS is simpler and faster (O(V+E) vs O(E log V)).
How to Identify
"Find shortest path", "Minimum cost to reach target", "Weighted positive graph".
Applying for software engineering roles? Free, no sign-up:
