Web Analytics

πŸ›£οΈ Dijkstra's Algorithm

Advanced ~35 min read

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

  1. Start at source vertex (distance = 0)
  2. Maintain distances to all vertices (initialized to ∞)
  3. Use priority queue (min heap) to track closest unvisited vertices
  4. Extract minimum (closest vertex)
  5. Relax edges: Update distances to neighbors
  6. 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

Output
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:

  1. Algorithm: Greedy approach using priority queue
  2. Time: O((V + E) log V) with heap, O(VΒ²) with array
  3. Space: O(V)
  4. Limitation: Only works with non-negative weights
  5. Applications: GPS navigation, network routing, pathfinding
  6. 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!