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. 1.Shortest Path in Binary Matrix
    medium
  2. 2.Word Ladder
    hard
  3. 3.Open the Lock
    medium
  4. 4.Network Delay Time
    medium
  5. 5.Cheapest Flights Within K Stops
    medium
  6. 6.Path With Minimum Effort
    medium
  7. 7.Swim in Rising Water
    hard
  8. 8.Minimum Cost to Make at Least One Valid Path in a Grid
    hard
  9. 9.Minimum Obstacle Removal to Reach Corner
    hard
  10. 10.Shortest Path with Alternating Colors
    medium
  11. 11.Bus Routes
    hard
  12. 12.Minimum Genetic Mutation
    medium
  13. 13.Snakes and Ladders
    medium
  14. 14.Rotting Oranges
    medium
  15. 15.01 Matrix
    medium
  16. 16.Bellman-Ford Shortest Path
    medium
  17. 17.Floyd-Warshall All-Pairs Shortest Path
    medium
  18. 18.Shortest Path in DAG
    medium
  19. 19.Dijkstra Shortest Path
    medium
  20. 20.0-1 BFS
    medium

Also Important

10 advanced variations worth practicing.

  1. 21.Minimum Knight Moves
    medium
  2. 22.Maze Shortest Path
    medium
  3. 23.Minimum Cost Path in Grid
    medium
  4. 24.Find the City With Smallest Number of Neighbors
    medium
  5. 25.Reachable Nodes in Subdivided Graph
    hard
  6. 26.Number of Ways to Arrive at Destination
    medium
  7. 27.Second Minimum Time to Reach Destination
    hard
  8. 28.Shortest Path Visiting All Nodes
    hard
  9. 29.Minimum Weighted Subgraph With Required Paths
    hard
  10. 30.A* Search — Practical Concept
    hard

How to Think

First define the state, legal edges, and what each edge costs. Then choose the algorithm.

  1. Every edge has the same cost?BFS
  2. Weights are only 0 or 1?0-1 BFS
  3. Weights vary but are non-negative?Dijkstra
  4. Negative edges may exist?Bellman-Ford
  5. Need distances between every pair?Floyd-Warshall
  6. 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 + relaxation

Go 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.

Special distinction: shortest path finds a minimum-cost route from a source; an MST connects every node with minimum total network cost. Dijkstra solves the former, while Kruskal and Prim solve the latter.
Visual Memory Rule
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 order

State, 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    → Dijkstra

Recover the actual route

When a distance improves:
parent[next] = current

At target:
target → parent → ... → start
reverse to get start → ... → target

When 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)
Initialize 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