Graphs, BFS and DFS, visualized.
Dots and the lines between them: roads, friendships, links. Then two ways to explore them: ring by ring with a queue, or deep first with a stack. A ghost walks every edge.
What is a graph?
A graph is a set of nodes (also called vertices) and edges that join pairs of them. Cities and roads. People and friendships. Web pages and links. Edges can be undirected (a road you can drive both ways) or directed (a one-way street, or “A follows B”). Some edges carry a number, a weight, like a distance; that is for a later lesson.
A tree is a connected graph with no cycles: there is exactly one path between any two nodes. The linked lists of lesson 1 were graphs all along: every node has one edge to the next.
01 — one item first
One node, then an edge.
Build a graph by hand. In Python the usual way to store one is a dict of lists: each node maps to the list of nodes it is joined to. That is an adjacency list.
Python
02 — two ways to store it
Adjacency list vs adjacency matrix.
The same graph, written down two ways. The list keeps each node’s neighbours. The matrix keeps a grid of yes/no for every pair. Ask both the same questions.
Adjacency list
looks: 0 · stores 14
Adjacency matrix
| A | B | C | D | E | F | G | |
|---|---|---|---|---|---|---|---|
| A | 0 | 1 | 1 | 0 | 0 | 0 | 0 |
| B | 1 | 0 | 0 | 1 | 1 | 0 | 0 |
| C | 1 | 0 | 0 | 0 | 0 | 1 | 0 |
| D | 0 | 1 | 0 | 0 | 0 | 0 | 1 |
| E | 0 | 1 | 0 | 0 | 0 | 1 | 0 |
| F | 0 | 0 | 1 | 0 | 1 | 0 | 0 |
| G | 0 | 0 | 0 | 1 | 0 | 0 | 0 |
looks: 0 · stores 49
7 nodes, 7 edges. Pick a question.
03 — breadth-first search
BFS: ring by ring, with a queue.
The ghost explores from A using the queue from lesson 2: the first node found is the first explored. So it finishes every node 1 edge away before any node 2 edges away.
Press Step to start at A.
Python · BFS
04 — depth-first search
DFS: deep first, with a stack.
Same graph, a stack instead of a queue. Here the stack is Python’s own call stack: dfs calls itself for each new neighbour, and each call waits, unfinished, on the stack until the calls above it return.
Press Step to call dfs on A.
Python · DFS
05 — your turn
Draw a graph, then search it.
Tap two nodes to join them, or tap a joined pair to cut the edge. Pick a start, then run BFS or DFS one step at a time.
H has no edges yet. Join it to something, then run a search.
Python · BFS
Python · DFS
06 — the classic bug
The search that forgot where it had been.
A graph can have cycles; a linked list cannot. Leave out the visited set and the ghost walks round the loop for ever.
Four nodes in a loop. Each lists its clockwise neighbour first.
Buggy
Fixed
07 — what BFS is for
Shortest path with BFS.
BFS reaches every node by a route with the fewest edges. Note who found each node (its parent), then walk the parents back from the goal.
From A to G. Tap another node to change the goal.
Python
08 — spot them in the wild
Graph or not? Real examples.
Ask: are there things, and links between them that matter? Pick one for each, then read why.
A city map of streets and junctions
Who is friends with whom
A shopping list
Course prerequisites
Web pages and the links between them
A family tree
Last week’s temperatures
Flights between airports
09 — the boss level
Number of islands.
A favourite interview question in disguise. Each land square is a node, joined to the land squares above, below, left and right (not diagonal). Count the separate pieces. A square is named by (row, column), counting from 0 at the top left.
Scan every square. Each new land square starts an island: flood-fill it with BFS so it is never counted again.
Python
10 — cheat sheet
BFS and DFS time complexity.
V is the number of nodes, E the number of edges. Both searches touch each node once and each edge from both ends: O(V + E).
| Job | Cost | In Python |
|---|---|---|
| BFS | O(V + E)memory O(V) for the queue and visited | collections.deque: append and popleft(). A list’s pop(0) is O(n). |
| DFS | O(V + E)memory O(V) for the stack and visited | Recursion is shortest. Python stops at about 1,000 nested calls (sys.getrecursionlimit()), so for deep graphs use a list as your own stack. |
| Shortest path, unweighted | O(V + E)BFS plus a parent for each node | parent = {start: None} |
| Adjacency list: memory | O(V + E) | dict of lists |
| Adjacency list: are A and B joined? | O(degree)scan A’s list | a dict of sets makes it O(1) |
| Adjacency matrix: memory | O(V²)every pair, joined or not | list of lists |
| Adjacency matrix: are A and B joined? | O(1) | matrix[a][b] |
| Number of islands | O(rows × cols) | BFS or DFS from each new land square |