DSA
advanced
Dijkstra's Algorithm
Software Engineer path · lesson 23 of 99A popular algorithm for finding the shortest path between nodes in a graph. It handles weighted edges and guarantees the shortest path for non-negative weights.
time O((V+E) log V)
space O(V)
Maze:
Tap or drag on the grid to
Algorithm
Switch and compare the expanded-cells count.
Show costs (g)
ExpandingFrontierExpandedNeighbour checkedShortest path
Start at (4,1), goal (4,11).
Code (running line highlighted)
- 1dist[start] = 0; pq = [(0, start)]
- 2while pq:
- 3 d, cell = pq.pop_min() # cheapest first
- 4 if cell == goal: return path
- 5 for nb in neighbours(cell):
- 6 if d + cost(nb) < dist[nb]: dist[nb] = d + cost(nb); parent[nb] = cell; pq.push(nb)
- 7return "no path"
- Cells expanded
- 0 / 105
- Frontier pushes
- 1 / 117
Invariant: Every expanded cell already has its final, cheapest distance.
Tap any element in the diagram to inspect its state at this step.
1 / 223
Keys: ← → step, Space play/pause. Predict mode pauses before key steps and asks what happens next.
Settle the closest node
Sequence
Order one iteration of Dijkstra’s algorithm with a priority queue.
Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.
- 1Drop a step here
- 2Drop a step here
- 3Drop a step here
- 4Drop a step here
- 5Drop a step here
5 pieces left to place
Test your knowledge
20 questions
Question 1 of 20
Score: 0
What happens if edge weights are negative?
When to reach for this
- Shortest Path in a **Weighted Graph** (non-negative weights)
- Network Routing Protocols (e.g., OSPF)
- Finding the cheapest cost to reach a destination
Interview Questions
Uber
Lyft
Meta
Google
Amazon
Microsoft
Bloomberg
Airbnb
LinkedIn
Meta
Bloomberg
Microsoft
Google
Amazon
Netflix
References & Further Reading
Love this visualization?
Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.
100% free • No credit card required