Graph Algorithms

Essential graph algorithms: traversals (BFS, DFS), shortest path (Dijkstra, Bellman-Ford), minimum spanning tree (Prim, Kruskal), topological sort, and network flow.

The data

Algorithms

NameCategoryTime complexitySpace complexityDescriptionUse casesPseudocodeNotesInput requirementsAlgorithmsPseudocode kahnOperationsVariants
Breadth-First Search (BFS)TraversalO(V + E)O(V)Visits nodes level by level using queue; finds shortest path in unweighted graphs.
  • Shortest path (unweighted)
  • Web crawling
  • Social network friend suggestions
  • Garbage collection (mark-sweep)
queue ← [start]; visited ← {start}; while queue not empty: node ← queue.pop(); for each neighbor of node: if neighbor not visited: visited.add(neighbor); queue.push(neighbor)Guarantees shortest path in unweighted graphs; uses more memory than DFSnullnullnullnullnull
Depth-First Search (DFS)TraversalO(V + E)O(V) (recursion stack or explicit stack)Explores as far as possible along each branch before backtracking; uses stack (implicit or explicit).
  • Cycle detection
  • Topological sorting
  • Maze solving
  • Connected components
  • Path existence
stack ← [start]; visited ← {}; while stack not empty: node ← stack.pop(); if node not visited: visited.add(node); for each neighbor of node: if neighbor not visited: stack.push(neighbor)Lower memory footprint than BFS; can get stuck in deep infinite branches (use iterative deepening or IDDFS)nullnullnullnullnull
Dijkstra's AlgorithmShortest PathO((V + E) log V) with min-heap, O(V²) with arrayO(V)Single-source shortest path for graphs with non-negative edge weights.nulldist[start] ← 0; pq ← min-heap of (distance, node); while pq not empty: d, u ← pq.pop(); if d > dist[u]: continue; for each edge u→v with weight w: if dist[u] + w < dist[v]: dist[v] ← dist[u] + w; pq.push(dist[v], v)Fails with negative weights (use Bellman-Ford); can be optimized with Fibonacci heap (O(V log V + E))Weighted directed/undirected graph; all edge weights ≥ 0nullnullnullnull
Bellman-Ford AlgorithmShortest PathO(V × E)O(V)Single-source shortest path handling negative weights; detects negative cycles.nulldist[all] ← ∞; dist[source] ← 0; repeat V-1 times: for each edge (u,v,w): if dist[u] + w < dist[v]: dist[v] ← dist[u] + w; // Check negative cycle: for each edge (u,v,w): if dist[u] + w < dist[v]: negative cycle existsSlower than Dijkstra but handles negatives; used in currency arbitrage detection; SPFA is optimization in practiceWeighted directed graph; negative weights allowed but no negative cycles reachable from sourcenullnullnullnull
Floyd-Warshall AlgorithmAll-Pairs Shortest PathO(V³)O(V²)All-pairs shortest paths for dense graphs; works with negative weights (no negative cycles).nullfor k from 1 to V: for i from 1 to V: for j from 1 to V: dist[i][j] ← min(dist[i][j], dist[i][k] + dist[k][j])Simple triple loop; good for dense graphs (V² space); transitive closure variantDirected/undirected weighted graph; no negative cyclesnullnullnullnull
Prim's AlgorithmMinimum Spanning TreeO(E log V) with min-heap, O(V²) with arrayO(V)Grows MST from a starting node; always adds cheapest edge connecting tree to new vertex.nullstart ← arbitrary node; mst_set ← {start}; while |mst_set| < V: find minimum weight edge (u,v) where u in mst_set, v not in mst_set; add v to mst_set; add edge to MSTLike Dijkstra but tracks vertices instead of distances; better for dense graphsnullnullnullnullnull
Kruskal's AlgorithmMinimum Spanning TreeO(E log E) (sorting dominates)O(V)Builds MST by adding edges in increasing weight order, skipping those that create cycles.nullsort edges by weight; mst ← {}; for each edge (u,v,w) in sorted edges: if find(u) ≠ find(v): mst.add(edge); union(u,v); // uses Disjoint Set (Union-Find)Better for sparse graphs; requires Union-Find with path compression (α(n) ≈ constant)nullnullnullnullnull
Topological SortOrderingO(V + E)O(V)Linear ordering of DAG vertices such that for every edge u→v, u comes before v.
  • Task scheduling (build systems, job queues)
  • Course prerequisites
  • Dependency resolution
  • Makefiles
nullGraph must be DAG; detects cycles; Kahn's also detects cyclesnull
  • Kahn's (BFS-based: indegree zero queue)
  • DFS-based (postorder reverse)
compute indegree of all nodes; queue ← all nodes with indegree 0; while queue not empty: u ← queue.pop(); order.append(u); for each neighbor v of u: indegree[v]--; if indegree[v] == 0: queue.push(v); if order.size < V: cycle detectednullnull
Union-Find (Disjoint Set)ConnectivityO(α(n)) per operation (amortized nearly O(1))O(n)Track partition of elements into disjoint sets; supports union and find operations.
  • Kruskal's MST
  • Connected components
  • Maze generation (Kruskal's)
  • Percolation
nullPath compression + union by rank gives amortized α(n) ≈ constant (inverse Ackermann); one of most optimized DSnullnullnull
Find
Returns representative (root) of set containing element; uses path compression
Union
Merges two sets; uses union by rank/size
null
Ford-Fulkerson (Max Flow)Network FlowO(E × max_flow) — Edmonds-Karp is O(V × E²)O(V + E)Computes maximum flow from source to sink in flow network; Ford-Fulkerson method with augmenting paths.
  • Bipartite matching
  • Assignment problems
  • Network capacity planning
  • Image segmentation (min-cut)
nullIntegral capacities → integral flow; Dinic's is faster in practice for dense graphsnullnullnullnull
  • Edmonds-Karp (BFS augmenting paths, O(VE²))
  • Dinic's (O(V²E), blocking flows)
  • Push-relabel (O(V³))

Graph representations

Adjacency matrix
Space
O(V²)
Pros
  • O(1) edge lookup
  • Simple
  • Good for dense graphs
Cons
  • O(V²) space even if sparse
  • Iterating neighbors O(V)
Adjacency list
Space
O(V + E)
Pros
  • Space efficient for sparse graphs
  • Fast neighbor iteration
Cons
  • O(degree(v)) edge existence check
  • Slower for dense graphs
Edge list
Space
O(E)
Pros
  • Simple
  • Good for algorithms that process all edges (Kruskal)
Cons
  • Slow edge lookup O(E)
  • No fast neighbor access

Fetch the same bytes

The static files are identical to what the API returns, but with no rate limit and no server round trip. Use the API when you want a query and a content type; use the files when you want to cache one document.

curl "https://yjtoon.com/api/dataset/graph-algorithms?format=toon"
const res = await fetch(
  "https://yjtoon.com/static-data/dataset/graph-algorithms.toon"
);
const toon = await res.text();

Rate limit: 120 requests per minute per IP, no key and no signup. API reference →

Topics

  • graphs
  • algorithms
  • bfs
  • dfs
  • dijkstra
  • mst
  • topological-sort
  • network-flow