Pattern #57
Shortest Path
Choose the right shortest-path algorithm from edge costs, master relaxation, reconstruct routes, model extra state, and avoid confusing shortest paths with minimum spanning trees.
Must Solve
20 core questions — solve these first.
- 1.Shortest Path in Binary MatrixEqual-cost 8-direction grid → BFSmedium
- 2.Word LadderImplicit unweighted graph → BFS / bidirectional BFShard
- 3.Open the LockState graph; every wheel turn costs 1 → BFSmedium
- 4.Network Delay TimeNon-negative weighted graph → Dijkstramedium
- 5.Cheapest Flights Within K StopsCost plus stops-used statemedium
- 6.Path With Minimum EffortMinimize maximum edge cost → modified Dijkstramedium
- 7.Swim in Rising WaterMinimax path → Dijkstra or binary search + reachabilityhard
- 8.Minimum Cost to Make at Least One Valid Path in a GridEdges cost only 0 or 1 → dequehard
- 9.Minimum Obstacle Removal to Reach CornerEntering a cell costs 0 or 1 → 0-1 BFShard
- 10.Shortest Path with Alternating ColorsState is (node, last edge color)medium
- 11.Bus RoutesModel stops and routes, then BFS by buses takenhard
- 12.Minimum Genetic MutationImplicit equal-cost mutation graph → BFSmedium
- 13.Snakes and LaddersBoard squares form an unweighted state graphmedium
- 14.Rotting OrangesAll rotten cells start together → multi-source BFSmedium
- 15.01 MatrixStart from every zero → multi-source BFSmedium
- 16.Bellman-Ford Shortest PathRelax all edges V − 1 times; detect negative cyclesmedium
- 17.Floyd-Warshall All-Pairs Shortest PathTry every node as an intermediate pointmedium
- 18.Shortest Path in DAGTopological order + relaxation → O(V + E)medium
- 19.Dijkstra Shortest PathMin heap always expands the cheapest known statemedium
- 20.0-1 BFSWeight 0 to deque front; weight 1 to backmedium
Also Important
10 advanced variations worth practicing.
- 21.Minimum Knight MovesEqual-cost moves on an infinite board → BFSmedium
- 22.Maze Shortest PathGrid cells are nodes; valid moves are edgesmedium
- 23.Minimum Cost Path in GridWeighted cells → Dijkstramedium
- 24.Find the City With Smallest Number of NeighborsMany pair queries → Floyd-Warshall or repeated Dijkstramedium
- 25.Reachable Nodes in Subdivided GraphDijkstra distances plus remaining moveshard
- 26.Number of Ways to Arrive at DestinationDijkstra with distance and ways arraysmedium
- 27.Second Minimum Time to Reach DestinationTrack two best arrival times per nodehard
- 28.Shortest Path Visiting All NodesBitmask BFS state: (node, visitedMask)hard
- 29.Minimum Weighted Subgraph With Required PathsCombine forward and reverse Dijkstra distanceshard
- 30.A* Search — Practical ConceptDijkstra guided by an admissible heuristichard
How to Think
First define the state, legal edges, and what each edge costs. Then choose the algorithm.
- Every edge has the same cost?BFS
- Weights are only 0 or 1?0-1 BFS
- Weights vary but are non-negative?Dijkstra
- Negative edges may exist?Bellman-Ford
- Need distances between every pair?Floyd-Warshall
- Graph is a DAG?Topological order + relaxation
Main decision rule
Equal cost → BFS
Only 0 / 1 → 0-1 BFS
Non-negative → Dijkstra
Negative edges → Bellman-Ford
All pairs → Floyd-Warshall
DAG → Topological order + relaxationGo Quick Reference — Shortest Path BFS
Use this equal-cost BFS template first. Switch to a heap only when edge costs vary.
func shortestPathBFS(graph [][]int, start int) []int {
dist := make([]int, len(graph))
for i := range dist { dist[i] = -1 }
dist[start] = 0
queue := []int{start}
head := 0
for head < len(queue) {
node := queue[head]
head++
for _, next := range graph[node] {
if dist[next] != -1 { continue }
dist[next] = dist[node] + 1
queue = append(queue, next)
}
}
return dist
}👉 Equal-cost graph: O(V + E) time and O(V) extra space.
Fewest edges ≠ cheapest cost
A ──10──→ B
A ──2──→ C ──3──→ B
Direct: 1 edge, cost 10
Via C: 2 edges, cost 5 ✓In weighted graphs, shortest means minimum total weight.
Relaxation
candidate = dist[u] + weight
if candidate < dist[v] {
dist[v] = candidate
parent[v] = u
}Found a cheaper route? Replace the old distance.
Algorithm Guide
BFS
O(V + E)Use when: Unweighted or equal-cost edges
Engine: FIFO queue
Explore distance 0, 1, 2, 3…; the first discovery has minimum edge count.
0-1 BFS
O(V + E)Use when: Every edge weight is exactly 0 or 1
Engine: Deque
Push zero-cost moves to the front and cost-one moves to the back.
Dijkstra
O((V + E) log V)Use when: Varying, non-negative weights
Engine: Min heap
Always process the state with the smallest known distance, then relax its edges.
Bellman-Ford
O(VE)Use when: Negative edges may exist
Engine: Repeated edge scans
Relax every edge V − 1 times; one more successful pass reveals a reachable negative cycle.
Floyd-Warshall
O(V³)Use when: All-pairs distances on a modest graph
Engine: Distance matrix
For each middle node k, test whether i → k → j improves i → j.
DAG Shortest Path
O(V + E)Use when: Directed acyclic graph, even with negative edges
Engine: Topological order
Process predecessors before successors and relax every outgoing edge once.
Equal cost → Queue waves
0 / 1 cost → Deque front or back
Varying non-negative cost → Min heap
Negative edge → Repeated relaxation
All pairs → Distance matrix
DAG → Topological orderState, Grids & Path Reconstruction
Grid as a graph
Cell → node
Valid move → edge
Move cost → edge weight
Equal move cost → BFS
0 / 1 cost → 0-1 BFS
Varying cost → DijkstraRecover the actual route
When a distance improves:
parent[next] = current
At target:
target → parent → ... → start
reverse to get start → ... → targetWhen a node is not the whole state
If arriving at the same node in different situations changes the legal next moves, include that situation in the state. Examples: (city, stopsUsed), (node, lastEdgeColor), or (cell, obstaclesRemaining).
Multi-source shortest path
For nearest-zero, nearest-hospital, or simultaneous-spread problems, enqueue every equal-cost source at distance 0 before BFS begins. One shared wave then computes distance to the nearest source.
Complexity Cheat Sheet
BFS O(V + E)
0-1 BFS O(V + E)
Dijkstra + heap O((V + E) log V)
Bellman-Ford O(VE)
Floyd-Warshall O(V³)
DAG shortest path O(V + E)dist[start] = 0 and every other distance to infinity. Only relax from reachable nodes, and choose an infinity value that cannot overflow when a weight is added.Common Interview Mistakes
- • Using BFS when edge costs differ — BFS minimizes edge count, not arbitrary total weight.
- • Using normal Dijkstra when negative edges are possible.
- • Marking a Dijkstra node visited like BFS before its best distance is finalized; stale heap entries should be skipped instead.
- • Forgetting the relaxation check before updating a distance.
- • Tracking only the node when stops, colors, keys, or remaining resources change future choices.
- • Confusing a source-to-target shortest route with a minimum spanning tree.
- • Returning only the distance when the interviewer asks for the actual route.
Interview Rules
Shortest Path → Minimum total cost
Equal weights → BFS
0 / 1 weights → 0-1 BFS
Non-negative → Dijkstra
Negative edges → Bellman-Ford
All pairs → Floyd-Warshall
DAG → Topological + relaxation
Better route → Relax the edge
Actual route → Store parent
Extra constraint → Add it to the state
Shortest path ≠ Minimum spanning tree💡 Golden Rule: Before choosing a shortest-path algorithm, inspect the edge costs first; the weight rules decide the algorithm.
Production Thinking
Maps and logistics → nodes are locations; weights may be time, fuel, toll, or risk.
Network routing → edge weights model latency, hop cost, or congestion.
Service dependencies → state may include retries, permissions, or remaining budget—not only the service name.
Production warning → real weights can change; stale routes may require recomputation, A*, bidirectional search, or dynamic updates.
Remember This
Model first: state + edges + weight
Equal move cost: BFS
Different non-negative cost: Dijkstra
Negative edge: Bellman-Ford
All pairs: Floyd-Warshall
0/1 cost: 0-1 BFS
Need route: parent map
Extra constraint: extra state