Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk6 min

Shortest Path Algorithms: How to Choose the Right Method

A practical guide to shortest-path algorithms: when to use BFS, Dijkstra, Bellman–Ford, DAG methods, A*, Floyd–Warshall, or Johnson.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose a shortest-path algorithm by checking four things: whether the graph is weighted, whether any weights are negative, whether the graph is acyclic, and whether you need one route or paths across the whole graph. For unweighted graphs, breadth-first search (BFS) finds a minimum-hop route. For weighted graphs with non-negative edges, Dijkstra is the usual starting point. Negative edges call for Bellman–Ford or, in a directed acyclic graph, a topological-order method; all-pairs queries often call for Floyd–Warshall or Johnson.

What does “shortest” mean?

A path’s cost is the sum of its edge weights. If edges have no weights, or you choose to treat them as equal-cost, shortest means the path with the fewest edges. In a directed graph, a path can follow only edges in their permitted direction. The objective should be clear before choosing an algorithm: minimum total cost and minimum number of hops are not interchangeable when weights differ. SciPy’s shortest_path documentation describes both weighted distance and the unweighted edge-count objective.

As an Amazon Associate I earn from qualifying purchases.

Which shortest-path algorithm should you use?

Start with your query scope, then check weight signs and graph structure. The complexity figures below are documented asymptotic guidance, not cross-platform runtime benchmarks; actual performance also depends on implementation and graph representation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Situation Starting point Documented guidance
Unweighted graph; minimize hops BFS O(V + E) in NetworkX’s overview. NetworkX
Weighted graph; all edge weights non-negative Dijkstra NetworkX gives O((V + E) log V) for its typical heap-based bound; the bound depends on data structure. NetworkX overview; Dijkstra notes
Negative edge weights may occur Bellman–Ford NetworkX lists O(VE); Boost documents negative-cycle detection. NetworkX; Boost.Graph
Directed acyclic graph (DAG), including graphs with negative edges Topological-order shortest paths Boost.Graph lists O(V + E). Boost.Graph
One target and a useful heuristic A* A heuristic can guide a single-target search and may make it faster than Dijkstra; this is not a guarantee for every heuristic or implementation. Boost.Graph
All pairs; dense graph Floyd–Warshall O(V³) in NetworkX’s overview. SciPy converts the input to a dense representation for this method. NetworkX; SciPy
All pairs; sparse graph, possibly with negative edges Johnson NetworkX and Boost document all-pairs use and negative-weight applicability when there is no negative cycle. Complexity expressions differ by source and implementation, so no single bound is stated here. NetworkX; Boost.Graph

Here, V is the number of vertices (nodes) and E is the number of edges. The table is a starting point, not a claim that one method is universally fastest. Dense versus sparse structure and the number of requested paths can change the practical choice.

#1 Best Overall
Sale
Introduction to Algorithms, fourth edition
  • color: White
  • INTRODUCTION TO ALGORITHMS, FOURTH EDITION

Choose the query scope before comparing runtimes

One source to every reachable node

Use a single-source method: BFS for minimum hops, Dijkstra for non-negative weighted edges, or Bellman–Ford if negative edges may occur. The result is a distance for each reachable node; store predecessor information as well if you need to reconstruct routes.

One source and one target

A single-target search may stop once the target is settled, depending on the algorithm and implementation. Bidirectional BFS or Dijkstra variants search outward from both ends and can reduce exploration in suitable cases; they are not automatically faster on every graph. If a meaningful heuristic estimates remaining cost to the target, A* is another option.

One source to the nearest of several targets

NetworkX documents a sentinel-node transformation: add a new node and connect each candidate target to it with a zero-cost edge, then find a path from the source to the new node. The recovered route identifies the nearest target. In an unweighted graph, use one edge from each target to the sentinel; that edge adds one hop, so subtract one from the reported distance. NetworkX explains this query pattern.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

All pairs of nodes

When distances or routes are needed between many or all pairs, consider an all-pairs method rather than repeating a single-source search without checking the cost. Floyd–Warshall is a direct choice often associated with dense graphs; Johnson is useful for sparse all-pairs graphs and supports negative edges provided there is no negative cycle. NetworkX and Boost document different complexity expressions, so compare the behavior of the library you plan to use rather than treating one expression as universal.

How the main algorithms work—and where they fail

BFS: minimum hops in an unweighted graph

Breadth-first search explores the graph in layers: first the source, then nodes one edge away, then nodes two edges away, and so on. The first time it reaches a node, it has found a minimum-edge-count route. Its O(V + E) bound is documented by NetworkX for unweighted shortest paths. It does not minimize arbitrary weighted cost unless all edges are treated as equal.

Dijkstra: non-negative weighted edges

“Dijkstra’s algorithm is a greedy, iterative algorithm,” says the NetworkX documentation. It repeatedly selects the unsettled node with the lowest tentative distance, finalizes that distance under the non-negative-weight condition, and relaxes its outgoing edges. Keep a predecessor for each improved distance if you need the actual route, not just its cost.

Dijkstra’s data structure changes its documented complexity. NetworkX lists O(V²) with a simple array, O((V + E) log V) with a binary heap, and O(V log V + E) with a Fibonacci heap. The better asymptotic expression for Fibonacci heaps does not guarantee faster real-world performance: NetworkX cautions that their constant overhead can make them slower at typical practical sizes. See NetworkX’s implementation notes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Bellman–Ford: negative edges and cycle detection

Bellman–Ford can handle negative edge weights and detect negative cycles. NetworkX lists O(VE) for the algorithm in its overview. A negative edge alone does not make the shortest path undefined; a reachable negative cycle does. If a walk can reach a negative cycle and then continue to a target, it can loop around that cycle repeatedly and lower its cost without limit. There is then no finite minimum walk cost for that target. NetworkX; Boost.Graph.

Best Value
Sale
Algorithm Design
  • Used Book in Good Condition

DAG shortest paths: exploit acyclic structure

If the directed graph has no cycles, process its nodes in topological order and relax outgoing edges as each node is reached. Boost.Graph lists O(V + E) for this specialized method, which can accommodate negative edge weights because acyclicity prevents a path from looping around a cycle. Boost.Graph’s overview describes the method.

Floyd–Warshall and Johnson: all-pairs choices

Floyd–Warshall updates the best known distances through each possible intermediate node; its documented NetworkX bound is O(V³). It is a straightforward all-pairs choice, especially when the graph is dense, but SciPy’s implementation converts the input graph to a dense representation, a relevant memory and representation cost for sparse inputs. NetworkX; SciPy v1.18.0.

Johnson is an all-pairs option for sparse graphs and can accommodate negative edges if no negative cycle exists. In standard presentations it reweights edges and then runs Dijkstra-style searches. Since the official NetworkX and Boost references present differing complexity expressions, treat their bounds as implementation-specific guidance rather than a universal formula.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Library-specific details to check

Algorithm names do not erase API differences. SciPy v1.18.0’s scipy.sparse.csgraph.shortest_path supports automatic method choice as well as named Floyd–Warshall, Dijkstra, Bellman–Ford, and Johnson methods; it can return distances and predecessor information. Its documentation warns that Dijkstra and Johnson do not correctly handle direction-dependent edge distances when called with directed=False. It also notes that when multiple valid solutions exist, output may vary with SciPy and Python version. These are SciPy API behaviors, not universal properties of the algorithms. SciPy v1.18.0 reference.

Version context matters when applying implementation notes: the retrieved NetworkX documentation identifies version 3.7.1rc0.dev0, SciPy’s cited manual is v1.18.0, and the Boost documentation uses a “latest” path without identifying an exact release. Check the documentation matching the version installed in your project.

Quick Recap

SaleBestseller No. 1
Introduction to Algorithms, fourth edition
Introduction to Algorithms, fourth edition
color: White; INTRODUCTION TO ALGORITHMS, FOURTH EDITION
$99.47
SaleBestseller No. 2
SaleBestseller No. 3
Bestseller No. 4
Algorithms
Algorithms
$142.22
SaleBestseller No. 5
Algorithm Design
Algorithm Design
Used Book in Good Condition
$223.93

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.