Algorithms
Dijkstra's Shortest Path
๐ Quick Reference
| Property | Value |
|---|---|
| Purpose | Shortest path from source to all vertices |
| Time Complexity | O((V + E) log V) with binary heap |
| Space Complexity | O(V) |
| Edge Weights | Non-negative only |
| Best For | GPS navigation, network routing, game pathfinding |
One-liner: Greedy algorithm finding shortest paths by always extending the closest unvisited vertex.
๐ฎ Interactive Visualizer
Watch Dijkstra's algorithm find shortest paths step by step:
Loading visualizer...
Try these operations:
- Select a source vertex
- Watch distance relaxation as algorithm progresses
- See the priority queue extract minimum distances
- Observe the shortest path tree being built
๐ง Implementation
Basic Dijkstra (Priority Queue)
JAVA(39 lines)CodeLoading syntax highlighter...
With Path Reconstruction
JAVA(59 lines)CodeLoading syntax highlighter...
๐ Complexity Analysis
| Implementation | Time | Space | Notes |
|---|---|---|---|
| Array (naive) | O(Vยฒ) | O(V) | Simple, good for dense graphs |
| Binary Heap | O((V+E) log V) | O(V) | Standard, good for sparse |
| Fibonacci Heap | O(V log V + E) | O(V) | Theoretical best |
Step-by-Step Example
Graph: A --5-- B | | 2 3 | | C --1-- D Starting from A: Step 1: dist = {A:0, B:โ, C:โ, D:โ} Visit A, update neighbors dist = {A:0, B:5, C:2, D:โ} Step 2: Extract min (C:2) Visit C, update neighbors dist = {A:0, B:5, C:2, D:3} Step 3: Extract min (D:3) Visit D, update neighbors dist = {A:0, B:5, C:2, D:3} (B via D = 3+3=6 > 5, no update) Step 4: Extract min (B:5) All neighbors visited Final: {A:0, B:5, C:2, D:3}
โ When to Use Dijkstra
Good Use Cases
- GPS/Maps - shortest driving route
- Network routing - packets through routers
- Game AI - pathfinding for NPCs
- Social networks - degrees of separation
- Flight planning - cheapest route
Avoid When
- Negative edge weights - use Bellman-Ford instead
- Unweighted graphs - BFS is simpler and faster
- All-pairs shortest paths - use Floyd-Warshall
- Very dense graphs - O(Vยฒ) array version may be better
๐ Algorithm Comparison
| Algorithm | Use Case | Time | Handles Negatives? |
|---|---|---|---|
| BFS | Unweighted | O(V+E) | N/A |
| Dijkstra | Non-negative weights | O((V+E) log V) | No |
| Bellman-Ford | Any weights | O(VE) | Yes |
| Floyd-Warshall | All pairs | O(Vยณ) | Yes |
| A* | Single target with heuristic | O((V+E) log V) | No |
๐งฉ Common Variations
Early Termination (Single Target)
JAVA(18 lines)CodeLoading syntax highlighter...
A* Enhancement (Heuristic)
JAVA(7 lines)CodeLoading syntax highlighter...
K Shortest Paths
JAVA(7 lines)CodeLoading syntax highlighter...
โ ๏ธ Common Pitfalls
1. Negative Edge Weights
JAVA(7 lines)CodeLoading syntax highlighter...
2. Not Skipping Processed Nodes
JAVA(12 lines)CodeLoading syntax highlighter...
3. Integer Overflow
JAVA(6 lines)CodeLoading syntax highlighter...
4. Missing Nodes in Graph
JAVA(5 lines)CodeLoading syntax highlighter...
๐ค Interview Tips
Q: Why doesn't Dijkstra work with negative weights?
"Dijkstra relies on the greedy property: once a node is visited with distance d, no shorter path exists. Negative edges can create shorter paths through already-visited nodes, breaking this assumption.
Q: How does Dijkstra differ from BFS?
"BFS treats all edges equally (unit weight), Dijkstra accounts for varying edge weights. BFS uses a simple queue; Dijkstra uses a priority queue ordered by distance.
Q: What's the time complexity with different data structures?
"With array: O(Vยฒ) - linear search for minimum. With binary heap: O((V+E) log V) - logarithmic extract-min. With Fibonacci heap: O(V log V + E) - theoretical best.
Q: How would you find the path, not just distance?
"Track predecessors in a parent map. When updating dist[v], also set parent[v] = u. Reconstruct path by following parent pointers from target to source.
๐ Series Navigation
Previous: Part 11: Graph Traversal (DFS & BFS)
Visualizer:
Dijkstra from @tomaszjarosz/react-visualizers