Shortest-path cues → BFS / Dijkstra / Bellman-Ford. How d… — Cracked Java
// Data Structures & Algorithms · Pattern Recognition for Interview Problems
SeniorTheory

Shortest-path cues → BFS / Dijkstra / Bellman-Ford. How do you choose?

When a problem asks for a shortest path, three algorithms compete. The cue that decides between them is the edge weights.

The decision table

OperationBestAverageWorstNote
When you see……useComplexityFails when
Unweighted edges (or all weight 1)BFSO(V + E)edges have varying weights
Non-negative weighted edgesDijkstra (heap)O((V + E) log V)any negative edge
Some negative edges, no neg cycleBellman-FordO(V·E)negative cycle (report it)
All-pairs shortest paths, denseFloyd-WarshallO(V³)very large V
Single target + good heuristicA*≤ Dijkstrano admissible heuristic

How to choose, step by step

  1. Are edges unweighted (or uniform)?BFS. Level order equals distance; the first time you reach a node is via a shortest path. This includes implicit graphs (word ladder, grid steps).
  2. Weighted, all non-negative?Dijkstra. The greedy "finalize the closest unvisited node" works because non-negativity guarantees you never improve a finalized distance later.
  3. Any negative edge?Dijkstra breaks (it may finalize a node before a cheaper negative-edge path is discovered). Use Bellman-Ford, which relaxes all edges V−1 times and can also detect negative cycles (a V-th relaxation that still improves something).
  4. Need every pair's distance and V is small?Floyd-Warshall, an O(V³) triple loop.
  5. Single source-to-target with domain knowledge (e.g. straight-line distance on a map)? → A*, which is Dijkstra guided by an admissible heuristic and explores far fewer nodes.

The two classic traps

  • 0-1 weights (edges weigh 0 or 1) → don't reach for full Dijkstra; 0-1 BFS with a deque is O(V + E).
  • "Cheapest within K stops" → not plain Dijkstra; it's a bounded relaxation, naturally Bellman-Ford-style or BFS with a hop counter, because the state includes stops-used.

Mark your status