Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Graph algorithms: traversal, shortest paths, spanning trees and flows

Graphs model anything made of things and the connections between them: roads, circuits, dependencies, networks of computers or people. This chapter covers lib_jsl_graph:

  • traversal and orderings (breadth- and depth-first search, components, topological order, strongly connected components);
  • shortest paths, from one source or between all pairs;
  • minimum spanning trees and the union-find structure;
  • maximum flow with its dual, the minimum cut.

The central questions

  • Directed or undirected, weighted or not? The same adjacency-list type holds all four kinds; each algorithm states which it needs (Dijkstra non-negative weights, spanning trees undirected graphs, topological sorting a directed acyclic graph).
  • One target, one source or all pairs? A* for one target, Dijkstra or Bellman–Ford for one source, Floyd–Warshall for all pairs.
  • Greedy or iterative? Dijkstra, Kruskal and Prim are greedy and correct for structural reasons; Bellman–Ford and the flow algorithms improve a solution until it cannot be improved.

Testing against SciPy and NetworkX

The references come from SciPy 1.17.1’s sparse.csgraph and NetworkX 3.7, on random graphs written out by book/generator/data/make_graph_refs.py and rebuilt identically by the generator:

Table 23.1. Graph algorithms against reference implementations.

computation (reference function)result
Dijkstra, 200 vertices, 1200 arcs, from three sources (csgraph.dijkstra)largest difference 0.0e0
Floyd-Warshall, same graph, two rows (csgraph.floyd_warshall)largest difference 0.0e0
Bellman-Ford with negative weights, 150 vertices (csgraph.bellman_ford)largest difference 0.0e0
minimum spanning forest weight, 400 vertices (csgraph.minimum_spanning_tree)Kruskal 12987.185, Prim 12987.185, SciPy 12987.185
connected components (csgraph.connected_components)14 (SciPy 14)
maximum flow, 100 vertices, 700 arcs (csgraph.maximum_flow)Edmonds-Karp 193, Dinic 193, SciPy 193
strongly connected components, 300 vertices (connected_components(connection="strong"))243 components (SciPy 243); same partition: true
lexicographically smallest topological order, 60 vertices (NetworkX)identical: true

In the library

All of these are in lib_jsl_graph (API reference).

You needUseEntry
A graph structure; traversal; components; an order for dependenciesGraph, breadth_first, depth_first, connected_components, topological_sort, strongly_connected_components, condensationTraversal and orderings
Cheapest pathsdijkstra, bellman_ford, a_star, floyd_warshallShortest paths
The cheapest connected network; disjoint setskruskal, prim, UnionFindSpanning trees
The most flow through a network; its bottleneckFlowNetwork::edmonds_karp, FlowNetwork::dinicMaximum flow