Shortest Path Algorithm Comparison: Two Questions Decide

Shortest Path Algorithm Comparison: Two Questions Decide

A shortest path algorithm comparison covering BFS, Dijkstra, Bellman-Ford, and Floyd-Warshall with a two question decision framework.

10 minutes
Advanced
What you will learn

How two questions about your graph determine the right algorithm

Why BFS works for unweighted graphs and fails for weighted ones

How Dijkstra's greedy invariant breaks with negative edge weights

When Floyd-Warshall beats running Dijkstra from every node

Which shortest path algorithm should you use? BFS, Dijkstra's, Bellman-Ford, and Floyd-Warshall are built for different graph types, and most resources explain them individually without ever telling you when each one applies. This shortest path algorithm comparison reduces the choice to two questions about your graph. The answers point to exactly one algorithm every time.

TL;DR
Two questions decide everything. Are edges weighted? Can weights be negative? BFS handles unweighted graphs. Dijkstra handles non negative weights. Bellman-Ford handles negative weights. Floyd-Warshall handles all pairs queries.

The shortest path algorithm comparison framework

Shortest path algorithms fall into four categories based on two graph properties: whether edges have weights, and whether those weights can be negative. Unweighted graphs use BFS. Non negative weighted graphs use Dijkstra's algorithm. Graphs with negative weights use Bellman-Ford. All pairs queries use Floyd-Warshall. That's the entire decision matrix.

Negative weights?
  • No
    N/A
  • Yes
    No
  • Yes
    Yes
  • Any (all pairs)
    Any
Algorithm
  • No
    BFS
  • Yes
    Dijkstra
  • Yes
    Bellman-Ford
  • Any (all pairs)
    Floyd-Warshall
Time complexity
  • No
    O(V + E)
  • Yes
    O((V + E) log V)
  • Yes
    O(V · E)
  • Any (all pairs)
    O(V³)

The first question eliminates BFS or enables it. The second separates Dijkstra from Bellman-Ford. And if you need shortest paths between every pair of nodes rather than from a single source, Floyd-Warshall is the right choice.

BFS as a shortest path algorithm

BFS finds shortest paths in unweighted graphs because it explores nodes layer by layer. All nodes at distance 1 get processed before distance 2, all at distance 2 before distance 3. The first time BFS reaches a node, it's found the shortest path to that node. There's no cheaper route hiding behind a longer queue entry.

Why does BFS break on weighted graphs? If edge A to B weighs 1 and edge A to C weighs 5, BFS treats both as "one step." It might process C before discovering a cheaper two edge path through B. The layer by layer guarantee assumes equal weight per edge. When that assumption fails, the guarantee goes with it.

ℹ️ Info
BFS runs in O(V + E), which makes it the fastest shortest path algorithm by a wide margin. When your graph is unweighted or all edges share the same weight, don't reach for Dijkstra. BFS is simpler and faster.

In interviews, BFS shortest path problems show up as grid traversals with uniform step weight, word transformation chains where each transformation counts as one step, and minimum step puzzles. The trigger is always the same: every move has the same weight. If you spot that constraint in the problem statement, BFS is your algorithm.

For a walkthrough of BFS mechanics and how it contrasts with DFS in traversal strategy, see our BFS vs DFS comparison.

Dijkstra's algorithm for non negative weighted graphs

When edges have different weights but none are negative, Dijkstra's algorithm is the standard choice. It maintains a priority queue of nodes sorted by current shortest known distance from the source. At each step, it extracts the node with the smallest distance and relaxes its outgoing neighbors, checking whether a shorter path exists through the current node.

The key invariant: Once a node gets extracted from the priority queue, its shortest distance is final. This is the greedy invariant, and it holds only when all edge weights are non negative.

The proof is one observation. If every weight is zero or greater, any path through additional edges can only increase the total distance. The node with the smallest known distance can't be reached more cheaply through some longer detour. That property, known as optimal substructure, is what makes the greedy approach valid.

Tracing Dijkstra on a 5-node graph

Consider finding the shortest distance from node A to node E in this graph.

`
A → B (4), A → C (2)
C → B (1), C → D (5)
B → D (3), D → E (1)
`
  1. Python

Notice that B's distance dropped from 4 to 3 when we processed C. That's relaxation at work. But once B was extracted at distance 3, that value was final. No later step changed it.

“The greedy invariant is the reason Dijkstra works and the reason it fails the moment a negative edge appears.”
Shortest path decision framework

Now imagine edge C to B had weight -3 instead of 1. After processing C, B's distance would become 2 + (-3) = -1. But we might've already finalized nodes based on the assumption that distances only grow. A negative edge can create shorter paths to nodes we already locked in, and that breaks the invariant entirely. This isn't some rare edge case. It's a hard constraint of the algorithm, and it's exactly when you reach for Bellman-Ford.

Codeintuition's understanding lesson for Dijkstra traces this invariant step by step, showing the priority queue state at every extraction. The identification lesson then covers the structural triggers that separate Dijkstra problems from BFS problems in interviews.

Bellman-Ford for graphs with negative weights

Bellman-Ford takes a fundamentally different approach. Instead of greedily finalizing nodes one at a time, it relaxes every edge in the graph V-1 times, where V is the vertex count.

Why V-1 passes? The longest possible shortest path in a graph with V nodes has at most V-1 edges. Each pass guarantees that shortest paths using K edges are correctly computed after K passes. After V-1 passes, all shortest distances are final regardless of edge processing order. The tradeoff is speed: Bellman-Ford runs in O(V · E), which is slower than Dijkstra's O((V + E) log V) for sparse graphs. You wouldn't choose it when Dijkstra works. But when negative weights exist, Bellman-Ford gives correct results where Dijkstra doesn't.

⚠️ Warning
Bellman-Ford has a secondary superpower: negative cycle detection. After V-1 passes, run one more pass over all edges. If any distance still decreases, the graph contains a negative cycle, meaning no finite shortest path exists. Dijkstra can't detect this at all.

In interviews, Bellman-Ford appears in currency exchange problems where negative log weights enable arbitrage detection, network optimization with weight penalties, and anywhere constraints explicitly mention negative weights. That constraint mention is your signal. If the problem says "weights can be negative," you've identified the algorithm before reading the rest of the problem. The negative cycle detection bonus is what makes Bellman-Ford show up in questions about arbitrage opportunities or infinite discount loops, two problem types where Dijkstra would silently produce wrong answers.

Floyd-Warshall for all pairs shortest paths

The three algorithms above solve the single source shortest path problem: distances from one starting node to all others. Floyd-Warshall solves something different. It computes shortest distances between every pair of nodes simultaneously.

It's a dynamic programming algorithm with a clean recurrence. For each pair of nodes (i, j), it checks whether routing through an intermediate node k produces a shorter path by comparing dist[i][j] against dist[i][k] + dist[k][j]. After considering all V possible intermediate nodes, the complete shortest distance matrix is done.

The Floyd-Warshall implementation is three nested loops.

The complexity is O(V³), which sounds steep. But consider the alternative: running Dijkstra from every node gives O(V · (V + E) log V). Dense graphs where E approaches push that to O(V³ log V), and Floyd-Warshall actually wins.

Sparse graphs with non negative weights do better with V runs of Dijkstra. Dense graphs or graphs with negative weights (but no negative cycles) favor Floyd-Warshall. The crossover depends on graph density, and most interview problems won't ask for all pairs computation. But when one does, you'll recognize it. Problems asking you to "find the shortest distance between every pair of cities" or "determine the minimum travel distance between all nodes" are Floyd-Warshall signals.

Comparison applied to interviews

The practical decision process for any shortest path problem:

  1. 1Is the graph unweighted? Use BFS. Don't overthink it.
  2. 2Are all weights non negative? Use Dijkstra.
  3. 3Can weights be negative? Use Bellman-Ford. If the problem asks about negative cycles, that confirms it.
  4. 4Do you need all pairs distances? Use Floyd-Warshall.

Where people get tripped up is separating #2 from #3. Most weighted graph problems in interviews use non negative weights, so Dijkstra is the default. But problems mentioning penalties, decreasing values, or exchange rates are hinting at negative weights. Read the constraints before you pick your algorithm.

This Describes You
  • Edges are unweighted or uniform weight, use BFS
  • Weighted with all non negative edges, use Dijkstra
  • Weighted with negative weights possible, use Bellman-Ford
  • Need shortest distances between all pairs, use Floyd-Warshall
  • Problem mentions "negative cycle," use Bellman-Ford with extra pass
This Doesn't Describe You

All items apply to you.

The broader skill here, reading problem constraints to pick the right algorithm class, is what separates pattern recognition from memorization. Codeintuition's graph course teaches each shortest path algorithm from its invariant rather than its implementation. You don't just learn Dijkstra's code. You learn why the greedy invariant holds, which constraints break it, and how to identify which algorithm a new problem needs before writing a single line.

Six weeks from now, you open a coding assessment. The problem describes a weighted directed graph with non negative edge weights and asks for the shortest route between two nodes. Instead of scrolling through four mental flashcards, you've already asked the two questions, confirmed the constraints, and started building the priority queue. The algorithm choice took five seconds because you understood the invariant, not the implementation.

Start with the two questions. The right algorithm follows.

Learn each algorithm from its invariant, not its implementation.

Codeintuition's Graph course teaches Dijkstra, BFS, and Bellman-Ford from the properties that make them correct, so you choose the right one in five seconds. Start with the free foundational courses for FREE

Dijkstra uses a greedy approach with a priority queue and only works when all edge weights are non negative. Bellman-Ford relaxes every edge V-1 times and handles negative weights correctly. Dijkstra is faster at O((V+E) log V) compared to Bellman-Ford's O(V·E), so you'd only use Bellman-Ford when negative edge weights are present in the graph.
No. BFS processes nodes layer by layer, treating each edge as having equal weight. In a weighted graph, a two edge path might weigh less than a one edge path, but BFS would still explore the one edge path first. For weighted graphs, you need Dijkstra when weights are non negative or Bellman-Ford when negative weights are possible.
Floyd-Warshall is the better choice when the graph is dense, meaning the edge count approaches , because its O(V³) complexity beats V runs of Dijkstra at O(V · (V+E) log V) in those cases. Floyd-Warshall also handles negative edge weights without negative cycles, which Dijkstra can't. It's simpler to implement when you need the complete distance matrix between all node pairs, and the three nested loops make the code straightforward compared to managing V separate priority queues.
After running V-1 relaxation passes, which is enough to finalize all shortest paths in a cycle free graph, you run one additional pass. If any node's distance still decreases during that extra pass, the graph must contain a negative cycle because a shorter path shouldn't exist after V-1 complete rounds of relaxation.
Dijkstra's algorithm is the most common because interview problems typically use non negative weights. BFS is a close second for unweighted graph and grid problems. Bellman-Ford and Floyd-Warshall appear less frequently, but knowing their constraints and when they're needed shows algorithmic depth that interviewers at top tier companies value. The ability to explain why you chose a particular algorithm matters more than implementing it quickly.
Was this helpful?