Free tools Windows power users keep installed

One-click scans. No signup required.

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 has a special structure such as being a directed acyclic graph, and whether you need one route or paths for every pair. For minimum hops in an unweighted graph, use breadth-first search (BFS); for non-negative weighted edges, use Dijkstra; for negative edges, use Bellman–Ford unless a DAG-specific method or an all-pairs method is a better fit.

What does “shortest” mean?

A path’s length is the sum of its edge weights when weights are supplied. If the graph is treated as unweighted, the objective is instead to minimize the number of edges, or hops. In a directed graph, a route may use an edge only in its permitted direction. These distinctions determine which routes are valid and what “shortest” optimizes. See SciPy’s shortest_path documentation.

Which shortest path algorithm should you use?

Start with the query you need, then account for weight signs and graph structure. The complexity figures below are documented algorithmic guidance, not a cross-platform runtime benchmark. Let V mean the number of vertices and E the number of edges.

Situation Starting point Documented guidance
Unweighted graph; minimize hops BFS NetworkX gives O(V + E) for unweighted shortest paths.
Weighted graph with non-negative weights Dijkstra NetworkX gives O((V + E) log V) for a typical binary-heap implementation; a simple array gives O(V²).
Negative edge weights may occur Bellman–Ford NetworkX gives O(VE); Boost notes that the algorithm detects negative cycles.
Directed acyclic graph (DAG) DAG shortest paths Boost lists O(V + E); this method does not require weights to be non-negative.
One target and a useful heuristic A* Boost describes the heuristic-guided, single-target use case; a good heuristic may improve search, but speed is not guaranteed for every heuristic or implementation.
All pairs; dense graph Floyd–Warshall NetworkX lists O(V³). SciPy converts the input to a dense representation for this method.
All pairs; sparse graph, possibly with negative weights Johnson NetworkX and Boost document all-pairs use and negative-weight applicability when there is no negative cycle. Their complexity expressions differ, so use the relevant library’s documentation for implementation-specific guidance.

These summaries are based on NetworkX’s shortest-path overview, Boost.Graph’s overview, and SciPy’s API reference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Introduction to Algorithms, fourth edition
  • color: White
  • INTRODUCTION TO ALGORITHMS, FOURTH EDITION

Choose by query scope

One source to all reachable vertices

This is a single-source query. BFS is the usual starting point when minimizing hops; Dijkstra is the common choice for non-negative weighted edges. Bellman–Ford is appropriate when negative weights are possible. The best fit also depends on whether the graph is a DAG.

One source-target pair

A single-pair query may avoid exploring as much of the graph as a full single-source result. NetworkX documents bidirectional BFS and Dijkstra variants for this scope. If a suitable heuristic is available for the target, A* is another option; its advantage depends on the heuristic and implementation, not merely the algorithm’s name.

One source to the nearest of several targets

NetworkX documents a sentinel-node transformation: add a new node and connect each target to it with a zero-cost edge, then search from the source to the new node. The discovered route identifies the nearest target. For an unweighted graph, each added edge contributes one hop, so subtract one from the reported distance to get the original source-to-target hop count.

All pairs

When the result must cover every source-target pair, consider Floyd–Warshall for a dense graph and Johnson for a sparse graph. If weights may be negative, Johnson is applicable only when the graph has no negative cycle. SciPy documents named methods as well as automatic method selection in its shortest_path API.

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

Unweighted graphs: use BFS for minimum hops

Breadth-first search explores vertices in increasing order of distance in edges. That makes the first discovered route to a vertex a minimum-hop route, assuming every edge counts equally. NetworkX documents O(V + E) for this unweighted shortest-path problem. If edges represent different costs, treating the graph as unweighted changes the question: BFS minimizes hops, not total cost.

Non-negative weighted graphs: how Dijkstra works

“Dijkstra’s algorithm is a greedy, iterative algorithm,” as NetworkX puts it in its Dijkstra documentation. It repeatedly selects the unsettled vertex with the smallest tentative distance, finalizes that distance, then relaxes its outgoing edges—updating a neighbor’s tentative distance when a cheaper route is found. The finalization step is guaranteed only when edge weights are non-negative.

To recover a route rather than just its distance, retain a predecessor for each vertex when its best-known route is updated. Follow the target’s predecessors back to the source, then reverse the sequence. NetworkX documents a Python binary-heap implementation. Its overview gives O((V + E) log V) for the typical heap-based bound, while its Dijkstra page distinguishes data structures: O(V²) for a simple array, O((V + E) log V) with a binary heap, and O(V log V + E) with a Fibonacci heap. NetworkX cautions that Fibonacci heaps’ constant overhead can make them slower in typical practical sizes despite the better asymptotic expression.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Negative weights and negative cycles

Does Dijkstra work with negative weights?

Do not rely on Dijkstra’s shortest-distance guarantee if any edge weight can be negative. Its greedy finalization assumes a vertex cannot later be reached by a cheaper route, an assumption that non-negative weights support. For graphs with negative edges, use Bellman–Ford for a single-source problem or consider Johnson for all pairs when there is no negative cycle.

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.
Best Value
Sale
Algorithm Design
  • Used Book in Good Condition

What a negative cycle changes

A negative cycle is a cycle whose edge weights sum to less than zero. If a source can reach such a cycle and the cycle can lead to a target, a walk to that target has no finite minimum cost: traverse the cycle repeatedly to reduce the total further. Bellman–Ford can detect negative cycles, as Boost documents. SciPy documents an error when a negative cycle is encountered. A negative edge alone is not a negative cycle; it is repeated traversal of a reachable negative cycle that makes the minimum walk cost undefined for affected targets.

When graph structure changes the choice

Directed acyclic graphs

A DAG allows vertices to be processed in topological order. Boost lists DAG shortest paths at O(V + E), including when weights are not restricted to non-negative values. This specialized option can avoid choosing a general-purpose algorithm solely on weight sign.

Dense and sparse graphs

Graph density matters most when choosing an all-pairs method. Floyd–Warshall is a straightforward O(V³) option commonly associated with dense graphs. SciPy converts the graph to a dense representation for its Floyd–Warshall method, a practical consideration when the input is sparse or memory is constrained. Johnson is aimed at sparse all-pairs graphs and supports negative weights if no negative cycle exists. NetworkX and Boost provide different complexity expressions for Johnson, so do not treat a single bound as universal across implementations.

Library-specific considerations

SciPy’s scipy.sparse.csgraph.shortest_path supports automatic method selection and named methods for Floyd–Warshall, Dijkstra, Bellman–Ford, and Johnson. It can return distances and predecessor information. Its documentation warns that Dijkstra and Johnson do not correctly handle direction-dependent edge distances if called with directed=False; choose the directed setting to match how the graph’s edges work. SciPy also notes that when multiple valid solutions exist, output can vary with SciPy and Python version.

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

These API details are specific to SciPy’s implementation, not universal properties of the underlying algorithms. For version context, the cited SciPy reference is for v1.18.0; the NetworkX latest documentation identifies version 3.7.1rc0.dev0, and the cited Boost page uses a “latest” path without stating an exact release.

Quick Recap

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

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.