Skip to main content

Graph Algorithms

Start by specifying the graph: directed or undirected, weighted or unweighted, sparse or dense, and whether negative edges or cycles are possible. Then state the output—reachability, one path, all distances, or a connecting subgraph.

Decision map

ProblemConditionsAlgorithmTime with common representation
Reachability / structuregeneral adjacency listsDFS or BFSO(V+E)O(V+E)
Minimum-edge pathunweighted / equal edge costsBFSO(V+E)O(V+E)
Single-source shortest pathsnonnegative weightsDijkstraO((V+E)logV)O((V+E)\log V)
Single-source shortest pathsnegative edges allowedBellman–FordO(VE)O(VE)
All-pairs shortest pathsdense or modest VVFloyd–WarshallO(V3)O(V^3)
Minimum spanning treeweighted undirected graphPrimO(ElogV)O(E\log V)
Minimum spanning treesortable edge listKruskalO(ElogE)O(E\log E)

Keep the objectives separate

A shortest-path tree minimizes source-to-vertex distances. A minimum spanning tree minimizes the total weight needed to connect all vertices. Neither objective implies the other, even though Dijkstra and Prim both use a priority queue.

Representation matters

Adjacency lists use O(V+E)O(V+E) storage and suit sparse graphs. An adjacency matrix uses O(V2)O(V^2) storage, provides constant-time edge lookup, and can simplify dense all-pairs algorithms. Complexity statements are incomplete without this choice.

Sources