← Graphs · guided lesson

Graphs: BFS & DFS

1 / 20 · story

the story

Graph (vertices + edges) and the adjacency list

Every tool here exists because something was too slow or broke without it. Here is what.

1736 · Leonhard Euler

The city of Königsberg had seven bridges over its river. Could you walk across every bridge exactly once? Euler answered in a paper for the St Petersburg Academy's 1736 volume (which only appeared in 1741) — for every possible map, not just this one. He threw away distances and shapes and kept only which land touches which bridge, then counted the bridges at each piece of land. (A complete proof of his rule came later, in Carl Hierholzer's paper of 1873.) Keeping only "what connects to what" is exactly what a graph is.

the problem it solved

Deciding whether every connection can be walked exactly once, for any map, without trying every route.

why it matters: without it

Every "what connects to what" question — routes, friend suggestions, build order — would need its own one-off data structure and its own bugs.

sources: The Euler Archive — E53: Solutio problematis ad geometriam situs pertinentis ↗ · Grötschel & Yuan — Euler, Mei-Ko Kwan, Königsberg, and a Chinese Postman (Documenta Mathematica, 2012) ↗

also in this chapter: Breadth-first search (BFS) · Depth-first search (DFS) · Grid as a graph — flood fill · Multi-source BFS · Bipartite check (two-colouring) · Directed cycle detection (three colours) · BFS on an implicit graph