Graph Algorithms
Shortest Path Algorithms
Shortest path algorithms find the cheapest route between nodes in a graph. Which one you need depends on three things: how many routes you want, whether edges can be negative, and whether you can guess the distance to the goal. Here is the comparison table first, then each algorithm in depth.
At a glance
A shortest path algorithm finds the route with the lowest total cost between nodes in a graph. A graph is a set of nodes (V) joined by edges (E), and each edge can carry a weight such as distance, time, or price. There is no single best algorithm. Each one trades speed against what it can handle.
The table compares six common choices. BFS handles unweighted graphs. Dijkstra handles non-negative weights. Bellman-Ford allows negative weights. Floyd-Warshall finds every pair at once. A* and bidirectional Dijkstra speed up the case where you only need one start and one goal.
| Graph Algorithms | Problem solved | Edge weights | Negative edges? | Time | Space | Best for |
|---|---|---|---|---|---|---|
| Dijkstra | Single-source: shortest paths from one node to all others | Non-negative | No | O((V + E) log V) with a binary heap; O(E + V log V) with a Fibonacci heap | O(V) | Road networks, routing, any graph with non-negative weights |
| Bellman-Ford | Single-source: shortest paths from one node to all others | Any, including negative | Yes, and it detects negative cycles | O(V · E) | O(V) | Graphs with negative edges, distance-vector routing, spotting arbitrage cycles |
| Floyd-Warshall | All-pairs: shortest paths between every pair of nodes | Any, including negative | Yes, but no negative cycles (it can detect them) | O(V³) | O(V²) | Small or dense graphs when you need every pair, transitive closure |
| A* Search | Single-pair: shortest path from one start to one goal | Non-negative | No | Depends on the heuristic; worst case O(b^d), usually far less than Dijkstra | O(b^d) in the worst case (stores the frontier) | Game pathfinding, maps and robots where a good distance guess exists |
| Bidirectional Dijkstra | Single-pair: shortest path from one start to one goal | Non-negative | No | Same O((V + E) log V) worst case; often visits far fewer nodes in practice | O(V) | Point-to-point queries on large road or social graphs |
| Breadth-First Search (BFS) | Single-source: fewest-edge paths from one node to all others | Unweighted (all edges equal) | Not applicable | O(V + E) | O(V) | Unweighted graphs, grids, mazes, degrees of separation |
Each algorithm in depth
Click any card for the full article with an interactive visualization, complexity analysis, code examples, and FAQ.
-
Dijkstra
Grows a set of finished nodes outward from the source. It always picks the unfinished node with the smallest known distance, then updates its neighbours. Once a node is finished, its distance is final. This only works if no edge is negative.
View interactive ↗ -
Bellman-Ford
Relaxes every edge, over and over, for V - 1 rounds. Each round fixes the paths that use one more edge. A final extra round reveals a negative cycle if one exists. It is slower than Dijkstra but handles negative edges.
View interactive ↗ -
Floyd-Warshall
Dynamic programming over all pairs at once. For each possible middle node k, it asks whether going through k shortens the path from i to j. Three nested loops make it very short to code.
View interactive ↗ -
A* Search
Dijkstra with a guide. It ranks nodes by cost so far plus a heuristic guess of the cost left to the goal, so it explores toward the target instead of in all directions. The path is optimal if the heuristic never overestimates.
View interactive ↗ -
Bidirectional Dijkstra
Runs Dijkstra from the source and from the target at the same time, going backward along edges from the target. It stops when the two searches meet. Each search covers about half the radius, so far fewer nodes are touched.
View interactive ↗ -
Breadth-First Search (BFS)
Visits nodes level by level using a queue. On an unweighted graph, the first time it reaches a node is by a path with the fewest edges. That makes it the simplest and fastest shortest-path method when every edge costs the same.
View interactive ↗
Which shortest path algorithm should I pick?
Ask these questions, in this order.
- Are all edges equal? Use BFS. It runs in O(V + E) and needs no heap.
- Can any edge be negative? Use Bellman-Ford for one source, or Floyd-Warshall for all pairs. Dijkstra will give wrong answers.
- Do you need every pair? Use Floyd-Warshall on small or dense graphs. On a big sparse graph with no negative edges, running Dijkstra from each node is usually faster.
- Do you need one start and one goal? Use A* if you have a good distance guess, such as straight-line distance on a map. Use bidirectional Dijkstra if you do not.
- Otherwise: Dijkstra is the safe default for one source and non-negative weights.
Why Dijkstra fails with negative edges
Dijkstra relies on one promise: when it finishes a node, no later path can be shorter. That is true only if adding an edge never lowers the total. A negative edge breaks it. A node could be finished with distance 5, and then a long path ending in an edge of weight -10 would reach it at distance 2. Dijkstra never goes back to fix it.
Bellman-Ford makes no such promise. It keeps relaxing every edge, so late improvements are caught. If a cycle adds up to a negative total, there is no shortest path at all, because you can loop forever and keep lowering the cost. Bellman-Ford spots this when edges can still be relaxed after V - 1 rounds. Adding a constant to every edge to remove negatives does not work, because it punishes paths with more edges.
Heuristics and admissibility in A*
A* scores each node with f = g + h. Here g is the cost paid so far and h is a guess of the cost left. A heuristic is admissible if it never overestimates the true remaining cost. Straight-line distance is admissible on a road map, since no road is shorter than a straight line. With an admissible heuristic, A* returns an optimal path.
A stronger property is consistency: h(a) is never more than the edge cost from a to b plus h(b). A consistent heuristic means A* never has to reopen a finished node. If h is always 0, A* becomes Dijkstra. A better guess means fewer nodes explored. An overestimating guess can make A* faster but lose the guarantee of the shortest path.
Bidirectional search and other speedups
In a graph where each node has about b neighbours, a search to depth d touches about b^d nodes. Two searches that each go to depth d/2 touch about 2 · b^(d/2). That is why bidirectional Dijkstra often explores far fewer nodes. The catch is the stop rule. The two searches meeting is not enough. You must wait until the best meeting path is proven shortest, or you can return a path that is not optimal.
Where these algorithms run in real systems
- Link-state routing: OSPF routers each build a map of the network and run Dijkstra to choose next hops.
- Distance-vector routing: RIP is based on the Bellman-Ford idea. Each router learns distances only from its neighbours, and a hop limit of 15 caps the cost of counting up.
- GPS and map apps: They do not run plain Dijkstra on the whole country. They add preprocessing, such as contraction hierarchies, that builds shortcut edges on top of Dijkstra-style search, often with bidirectional queries. Answers come back in milliseconds.
- Games and robots: A* on a grid or navigation mesh is the standard choice, with a distance heuristic.
- Social networks: Degrees of separation are BFS on an unweighted graph.
Frequently asked questions
What is the difference between Dijkstra and Bellman-Ford?
Dijkstra is faster, at O((V + E) log V) with a binary heap, but it needs non-negative edge weights. Bellman-Ford takes O(V · E) but allows negative edges and can detect negative cycles. If your weights are never negative, use Dijkstra.
What is the difference between Dijkstra and A*?
Dijkstra explores outward in all directions from the start. A* adds a heuristic that estimates the distance to the goal, so it explores mostly toward the goal. A* finds one start-to-goal path; Dijkstra finds paths to every node. With an admissible heuristic, both return a shortest path.
Should I use Floyd-Warshall or Dijkstra?
Use Floyd-Warshall when you need the distance between every pair of nodes and the graph is small or dense, since it is O(V³) and very short to code. Use Dijkstra from one source, or from each node on a large sparse graph with no negative edges, where V runs of Dijkstra beat V³.
Can Dijkstra handle negative edge weights?
No. Dijkstra assumes a finished node can never be improved, and a negative edge breaks that. It can return wrong distances. Use Bellman-Ford instead, or Floyd-Warshall for all pairs. Some Dijkstra variants re-open nodes, but they lose the usual running time.
Is BFS a shortest path algorithm?
Yes, on unweighted graphs. BFS finds the path with the fewest edges in O(V + E). On a weighted graph it does not minimize total weight, so use Dijkstra there. If all weights are equal, BFS is simpler and faster.
What makes a heuristic admissible in A*?
It never overestimates the true remaining cost to the goal. Straight-line distance on a road map is admissible because no path is shorter than a straight line. Admissible heuristics keep A* optimal. If the heuristic is also consistent, A* never needs to revisit a finished node.
How does bidirectional Dijkstra speed up search?
It runs one search forward from the source and one backward from the target, and stops when they meet. Each covers roughly half the distance, so the area explored shrinks a lot. Its worst-case bound is the same as Dijkstra, but it usually touches far fewer nodes.
Which shortest path algorithm do routers and GPS use?
OSPF routers use Dijkstra. RIP uses the Bellman-Ford idea. GPS apps use Dijkstra-style search made much faster with preprocessing such as contraction hierarchies. Game engines mostly use A*.