AlgoFrames

Graphs

Vertices and edges: traversal, shortest paths, spanning trees, connectivity and network flow.

Basics

Graph vocabulary, ways to store a graph, and graphs hidden inside grids and puzzles.

Traversal

Visit every vertex with BFS and DFS, then find components, cycles and orderings.

Shortest paths

Fewest edges or least total weight: BFS, Dijkstra, Bellman-Ford, Floyd-Warshall and A*.

  • Shortest paths in unweighted graphs; path reconstruction In an unweighted graph BFS finds shortest paths. Distance labels spread outward and parent arrows trace each path back to the source.
  • Dijkstra's algorithm Dijkstra’s algorithm finds shortest paths with non-negative weights. It settles the closest unsettled vertex and relaxes its edges using a…
  • Bellman-Ford and negative edges Bellman-Ford relaxes every edge n − 1 times, so it handles negative weights. One more round that still improves a distance reveals a…
  • 0-1 BFS and multi-source BFS When edge weights are only 0 or 1, a deque replaces the priority queue. Multi-source BFS starts from many sources at once, as in rotting…
  • Floyd-Warshall: all pairs Floyd-Warshall finds shortest paths between every pair of vertices. The distance matrix updates once for each vertex allowed as a midpoint.
  • A* search with heuristics A* adds a heuristic estimate of the remaining distance to Dijkstra’s cost. A good heuristic aims the search at the goal and expands fewer…

Spanning trees and connectivity

Connect everything at minimum cost, and find the parts a graph cannot lose.

  • Kruskal's algorithm Kruskal’s algorithm builds a minimum spanning tree by taking edges from cheapest to most expensive, skipping any edge that would form a…
  • Prim's algorithm Prim’s algorithm grows a minimum spanning tree from one vertex, always adding the cheapest edge that reaches a new vertex.
  • Strongly connected components: Kosaraju and Tarjan In a directed graph a strongly connected component is a set where every vertex reaches every other. Find them with Kosaraju’s or Tarjan’s…

Flow and matching

Push as much as possible through a network, and pair items up with matchings.