Algorithms

Dijkstra's Shortest Path

๐Ÿ“‹ Quick Reference

PropertyValue
PurposeShortest path from source to all vertices
Time ComplexityO((V + E) log V) with binary heap
Space ComplexityO(V)
Edge WeightsNon-negative only
Best ForGPS 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:
  1. Select a source vertex
  2. Watch distance relaxation as algorithm progresses
  3. See the priority queue extract minimum distances
  4. Observe the shortest path tree being built

๐Ÿ”ง Implementation

Basic Dijkstra (Priority Queue)

JAVA(39 lines)
Code
Loading syntax highlighter...

With Path Reconstruction

JAVA(59 lines)
Code
Loading syntax highlighter...

๐Ÿ“Š Complexity Analysis

ImplementationTimeSpaceNotes
Array (naive)O(Vยฒ)O(V)Simple, good for dense graphs
Binary HeapO((V+E) log V)O(V)Standard, good for sparse
Fibonacci HeapO(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

AlgorithmUse CaseTimeHandles Negatives?
BFSUnweightedO(V+E)N/A
DijkstraNon-negative weightsO((V+E) log V)No
Bellman-FordAny weightsO(VE)Yes
Floyd-WarshallAll pairsO(Vยณ)Yes
A*Single target with heuristicO((V+E) log V)No

๐Ÿงฉ Common Variations

Early Termination (Single Target)

JAVA(18 lines)
Code
Loading syntax highlighter...

A* Enhancement (Heuristic)

JAVA(7 lines)
Code
Loading syntax highlighter...

K Shortest Paths

JAVA(7 lines)
Code
Loading syntax highlighter...

โš ๏ธ Common Pitfalls

1. Negative Edge Weights

JAVA(7 lines)
Code
Loading syntax highlighter...

2. Not Skipping Processed Nodes

JAVA(12 lines)
Code
Loading syntax highlighter...

3. Integer Overflow

JAVA(6 lines)
Code
Loading syntax highlighter...

4. Missing Nodes in Graph

JAVA(5 lines)
Code
Loading 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


Visualizer: Dijkstra from @tomaszjarosz/react-visualizers