Begin Algo
Graph Algorithms · Comparison

Shortest-path algorithms compared

BFS, Dijkstra, Bellman-Ford, Floyd-Warshall and DAG shortest paths: edge weights, negative edges, single-source or all-pairs — one table to pick the right one.

AlgorithmTimeSpaceWeightsNegative edgesScopeDifficulty
BFSBreadth-first searchO(V+E)O(V)All equal (unweighted)Single sourceIntro
DijkstraSingle-source shortest pathsO((V+E) log V)O(V)Non-negativeSingle sourceIntermediate
Bellman-FordShortest paths with negative weightsO(VE)O(V)Any✓, and detects negative cyclesSingle sourceHard
Floyd-WarshallAll-pairs shortest pathsO(V³)O(V²)Any✓ (negative cycle shows on the diagonal)All pairsHard
Shortest Path in DAGShortest paths on a DAGO(V+E)O(V)Any✓ (acyclic, so no negative cycles)Single sourceIntermediate

When to pick which

Choosing guide

  • Unweighted → BFS. Non-negative → Dijkstra. Negative edges → Bellman-Ford. Acyclic → DAG relaxation. All pairs, small V → Floyd-Warshall.
  • Weights are only 0 and 1 → 0-1 BFS (a deque: weight 0 to the front, weight 1 to the back), O(V+E) without Dijkstra's log.
  • All pairs but large V and sparse edges → run Dijkstra from every vertex; V·(V+E) log V is usually far better than V³.
  • Longest path → NP-hard on general graphs; on a DAG negate the weights and run shortest path, or take max along topological order.
  • Only reachability, distance irrelevant → DFS or Union-Find is enough; skip shortest paths entirely.