π£οΈ Dijkstra's Algorithm
You're planning a road trip. Some routes are longer but faster highways, others are shorter but slower. Dijkstra's algorithm finds the optimal route considering distances, just like GPS navigation finds the best path considering real-world road conditions!
The Weighted Path Problem
BFS finds shortest path in unweighted graphs, but real-world graphs have weights (distances, costs, latencies). Dijkstra's solves this:
Real-World Applications
- GPS Navigation: Find fastest route considering distances and speeds
- Network Routing: Route packets through least-latency paths
- Flight Routes: Find cheapest flight path
- Game Pathfinding: Navigate characters through weighted terrain
- Resource Allocation: Optimize resource distribution
How Dijkstra's Works
Greedy Algorithm
- Start at source vertex (distance = 0)
- Maintain distances to all vertices (initialized to β)
- Use priority queue (min heap) to track closest unvisited vertices
- Extract minimum (closest vertex)
- Relax edges: Update distances to neighbors
- Repeat until all vertices processed
Key insight: Greedy choice (closest vertex) is always optimal!
See Dijkstra's in Action
Why Priority Queue?
Efficiency Gain
- Without PQ: O(VΒ²) - scan all vertices to find minimum
- With PQ (heap): O((V+E) log V) - extract min in O(log V)
- Better for sparse graphs: E << VΒ²
Important Limitations
Non-Negative Weights Only!
Dijkstra's algorithm cannot handle negative edge weights.
If negative weights exist, use Bellman-Ford algorithm instead.
Why? Greedy choice assumes distances only decrease, but negative edges can decrease distances after a vertex is processed.
The Complete Code
Click Run to execute your code
Dijkstra vs BFS
Comparison
| Aspect | BFS | Dijkstra |
|---|---|---|
| Graph Type | Unweighted | Weighted (non-negative) |
| Data Structure | Queue | Priority Queue |
| Time Complexity | O(V + E) | O((V + E) log V) |
| Shortest Path | Yes (unweighted) | Yes (weighted) |
Path Reconstruction
Track parent of each vertex during algorithm execution. After completion, reconstruct path by following parents from destination to source.
Summary
What You've Learned
Dijkstra's algorithm finds shortest path in weighted graphs:
- Algorithm: Greedy approach using priority queue
- Time: O((V + E) log V) with heap, O(VΒ²) with array
- Space: O(V)
- Limitation: Only works with non-negative weights
- Applications: GPS navigation, network routing, pathfinding
- Key insight: Greedy choice (closest vertex) is always optimal
What's Next?
You've mastered Dijkstra's! Next, we'll explore Bellman-Ford Algorithm - which handles negative weights and detects negative cycles, perfect for currency arbitrage and routing protocols!
Enjoying these tutorials?