Lesson 2 of 6
Depth-first search
Depth-first search walks a graph by going as deep as it can, then backing up to the last place with a path it has not tried. With a visited set it reaches every node once, and counting how many searches you start counts the islands on a map.
Trace a recursive depth-first search and say which calls are waiting at every step
Write depth-first search on an adjacency list and on a grid, marking cells with a set or by changing them
Replace the recursion with a stack of your own when the search could go thousands of calls deep
Count connected groups, such as islands, by counting the searches you start
State the cost of a graph search: O(V + E) time, or O(rows × cols) on a grid
A map arrives as a grid of 1s (land) and 0s (water):
1 1 0 1
0 1 0 1
1 0 0 0
How many islands? You see three at a glance: the bent one at the top left, the two cells on the right, and the lone cell at the bottom left. You found each one by putting a finger on land and sliding it until water stopped you. The computer has no glance. It looks at one cell at a time, so it needs a walk that starts on one piece of land, reaches every piece joined to it, and knows when it is done.
One walk that does this is depth-first search. It answers "what can I reach from here?" on any graph: cells on a map, pixels in an image, tables in a lineage graph. You have run it once already: the spread at the end of the last lesson took the newest node off its stack, and that is what makes a search depth first. This lesson writes it the short way, with recursion, takes it onto grids, and uses it to count groups like these islands.
Go deep, then back up
Which nodes can you reach from A? First, the words from the last lesson. A graph is a set of nodes joined by edges. Two nodes joined by an edge are neighbors. An adjacency list stores a graph as a dict from each node to the list of its neighbors. Here is one with five nodes:
| Node | Neighbors |
|---|---|
| A | B, C |
| B | A, D |
| C | A, D |
| D | B, C, E |
| E | D |
From A you can go to B, then D, then C, and arrive back at A without using any edge twice: a cycle, in the last lesson's words. And every edge here works both ways, so a search could also step from A to B and straight back. That is why a search needs a notebook.
Depth-first search (DFS) follows one rule: step to a neighbor you have not visited yet, and keep going. When every neighbor of the current node is visited, you are at a dead end: back up to the node you came from and try its next neighbor. The search ends when the start itself has no unvisited neighbor left.
The notebook is a set, seen. Mark a node the moment you reach it, before you look at its neighbors. Without the mark, nothing tells the search that A is done, so it can go A, B, A, B, and never reach anything new.
Recursion fits the rule exactly. dfs(node) marks the node, then calls itself on each neighbor not in seen. Returning is the backing up: when a call has tried all its neighbors, it returns, and Python goes back to the call that made it, the one just below it on the call stack (the pile of unfinished calls, newest on top). The list order records the visits. Before you step through, guess the order.
graph = {"A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D"], "D": ["B", "C", "E"], "E": ["D"]}seen = set()order = []def dfs(node):seen.add(node)order.append(node)for neighbor in graph[node]:if neighbor not in seen:dfs(neighbor)dfs("A")print(order)
(nothing printed yet)C is A's neighbor, but it was visited fourth, through D. The search followed one path as far as it went before it looked at A's second neighbor, and by then C was marked. The open calls are the way back: at the deepest point four were open, one for each node on the path A, B, D, C, and each return steps one node back along it.
V is the usual letter for the number of nodes (from vertex, the other name for a node), so O(V + E) is the same cost as the last lesson's O(n + E).
Now predict one. The neighbor lists decide the order.
Read the search and type exactly what it prints, one node per line.
graph = {"A": ["C", "B"], "B": ["A", "D"], "C": ["A", "D"], "D": ["C", "B"]}
seen = set()
def dfs(node):
seen.add(node)
print(node)
for neighbor in graph[node]:
if neighbor not in seen:
dfs(neighbor)
dfs("A")
Take the mark out and see what happens.
This version has no seen set:
graph = {"A": ["B"], "B": ["A"]}
def dfs(node):
print(node)
for neighbor in graph[node]:
dfs(neighbor)
dfs("A")
What happens?
Choose one answer, then check.
Then write the search from a blank function. Edges may be one-way here, and the code does not change for that.
Write reachable(graph, start), which returns a sorted list of every node you can reach from start by following edges, start included. graph is a dict from each node to the list of nodes you can step to from it, and every node is a key. Edges may be one-way: "A": ["B"] lets you step from A to B, and only "B": ["A"] would let you step back.
Use a helper dfs(node) defined inside reachable, so it can read graph and add to seen, the way the recursion lesson kept memo inside fib.
raise NotImplementedError, then press Run tests. Each check says what it expects.Depth-first on a grid
How does the search walk a map, an image or a maze? The last lesson showed that a grid is a graph: each cell (row, column) is a node, and its neighbors are the cells up, down, left and right of it. Here is the reminder of the loop that finds them, with nr, nc naming the neighbor's row and column:
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] # down, up, right, left
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols:
... # (nr, nc) is a neighbor of (r, c)
Keep both halves of the bounds check. Without 0 <=, row -1 gets through, and grid[-1] quietly reads the last row instead of failing.
There are two ways to mark a cell: a set of (row, column) pairs, or a change to the cell itself. A paint program's bucket tool does the second. It paints a region: the clicked pixel plus every pixel joined to it by steps up, down, left or right through pixels of the same color. A painted pixel no longer has the old color, so nothing steps back into it. Changing cells saves the memory of a set, but it changes the caller's grid, so ask the interviewer first.
Here is the bucket tool as a recursive DFS: it paints every 1 joined to (0, 0) with a 5. The grid draws image, and a cell changes the moment it is painted. Before you step through, guess which cell is painted last.
image = [[1, 1, 0], [1, 1, 0], [0, 1, 1]]rows, cols = 3, 3directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] # down, up, right, leftdef paint(r, c):image[r][c] = 5for dr, dc in directions:nr, nc = r + dr, c + dcif 0 <= nr < rows and 0 <= nc < cols and image[nr][nc] == 1:paint(nr, nc)paint(0, 0)print(image)
(nothing printed yet)The order came from directions. Down comes before right, so the search went down from (0, 0) first and reached (0, 1), right next to the start, last, from (1, 1). Another order of directions paints the cells in another order, but never changes which six cells get painted. Each cell is painted once and checks four neighbors: O(rows × cols) time. The waiting calls can number as many as the region's cells: O(rows × cols) stack space in the worst case.
Now rebuild the painter with the image and both colors as parameters, and think about where the painting line belongs.
Put the lines in order to build fill(image, r, c, old, color), which paints every pixel joined to (r, c) that has the color old, using color. Assume old and color are different. Indentation is part of each line. Two lines do not belong.
Add lines from the list below, in order.
def fill(image, r, c, old, color):nr, nc = r + dr, c + dcimage[r][c] = colorif image[nr][nc] == old and 0 <= nr < len(image) and 0 <= nc < len(image[0]):for dr, dc in [(1, 0), (-1, 0), (0, 1), (0, -1)]:if 0 <= nr < len(image) and 0 <= nc < len(image[0]) and image[nr][nc] == old:if nr < len(image) and nc < len(image[0]) and image[nr][nc] == old:fill(image, nr, nc, old, color)
The recursive versions in this lesson's problem solutions use a second style: call on all four neighbors and let each call check its own cell first. It is shorter to write and a fine answer, but it pays a call for every neighbor, even the ones that return at once.
This painter calls itself on all four neighbors and lets each call check its own cell first:
def paint(r, c):
if r < 0 or r >= rows or c < 0 or c >= cols:
return # off the image
if image[r][c] != old:
return # another color, or painted already
image[r][c] = color
paint(r + 1, c)
paint(r - 1, c)
paint(r, c + 1)
paint(r, c - 1)
The image is 2 by 2 and every pixel is 1, with old = 1 and color = 5. The first call is paint(0, 0). How many calls of paint happen in all, counting that first one?
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
So far: DFS marks a node, then goes to an unvisited neighbor as deep as it can, and a call returning is the search backing up. On a grid, neighbors come from directions plus a bounds check, and the mark is a set or a changed cell.
A stack of your own
How deep can the waiting calls pile up? As deep as the region is large. From a corner of a 50 by 50 image of one color, the recursive painter goes 2,500 calls deep; from a corner of a 300 by 300 map of all land, 90,000. Plain Python stops at about 1,000 nested calls by default with a RecursionError, and this lab allows 5,000. The image passes here but not in plain Python; the map fails in both.
The fix is the last lesson's spread: keep the waiting cells in a list used as a stack, last in, first out, where append pushes onto the top and pop() takes the top. Push the start. Until the stack is empty, pop a cell and push its unvisited neighbors. The newest cell always comes off first, so the search goes on from wherever it arrived last: depth first.
The figure runs that loop on a grid of open cells (.) and walls (#) from S, checking neighbors in its own order: up, right, down, left. The stack is a column with its top at the top, and each cell gets a visit number when it comes off. Watch (1, 0).
The widget counts a cell as visited when it comes off the stack. The code below marks a cell when it goes on, as the problems do, so no cell is ever pushed twice. Both reach the same cells.
Here is that code on the painting grid, with 1 for land and 0 for water. The stack is drawn top first. Before you step through, guess which cell comes off last.
def explore(grid, start):rows, cols = len(grid), len(grid[0])directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] # down, up, right, leftseen = {start}stack = [start]while stack:r, c = stack.pop()for dr, dc in directions:nr, nc = r + dr, c + dcif 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1 and (nr, nc) not in seen:seen.add((nr, nc))stack.append((nr, nc))return len(seen)
(nothing printed yet)The same six cells as the painting trace, in another order: (0, 0), (0, 1), (1, 1), (2, 1), (2, 2), (1, 0). Of the two neighbors of (0, 0), the one pushed second came off first. The order can differ from the recursive one, but the search always goes on from the newest cell, and it reaches exactly the same set.
Many rounds have no run button, so run the stack once by hand.
Run the stack version by hand on this map, starting at (0, 0). Use the lesson's order of directions: down, up, right, left. Mark a cell when you push it. After each pop and the pushes that follow it, write the cell you popped and the stack, bottom first, as Python prints a list.
1 1 1
1 0 1
What visit number does (1, 0) get, counting (0, 0) as visit 1?
Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
The first problem is the bucket tool for any start and any color. Painting is the mark. Read the third example first: one case breaks that mark.
Debrief. The trap is a new color equal to the old one: painted pixels still look unpainted, so they push each other again and again and the stack never empties. Returning the image unchanged at the top avoids it, and is the right answer.
Count the searches
Back to the map: how many islands? One search marks one whole group: everything reachable from its start. So walk over every node, and at each node no search has reached, start a search and add one to the count. These groups are connected components: groups of nodes that can all reach each other, with no edge leaving the group.
The trace counts the groups among six nodes: A, B and C in a chain, D alone, and E with F. All the searches share seen, so the scan skips nodes an earlier search marked. Before you step through, guess how many times count += 1 runs.
graph = {"A": ["B"], "B": ["A", "C"], "C": ["B"], "D": [], "E": ["F"], "F": ["E"]}seen = set()def dfs(node):seen.add(node)for neighbor in graph[node]:if neighbor not in seen:dfs(neighbor)count = 0for node in graph:if node not in seen:dfs(node)count += 1print(count)
(nothing printed yet)On a map, the nodes are cells and the scan is two loops, over the rows and then the columns. Every land cell not in seen starts a search. Cells that touch only at a corner are not neighbors: unless a path of side-by-side land joins them, they are on different islands.
How many islands does this map hold? Land is 1 and water is 0. Two land cells are on the same island only if you can walk between them by steps up, down, left or right, on land.
1 1 0 0 1
0 1 0 1 1
1 0 0 0 0
0 0 1 1 0
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
This is the lesson's flagship problem: the counting scan wrapped around the stack search. One change to the stack search: seen moves outside it, so every search adds to the same set. Define explore(start) inside your function, the way dfs sat inside reachable, so it can read grid and add to seen. Here is the scan, with the search left as one call:
count = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == "1" and (r, c) not in seen:
explore((r, c)) # the stack search: adds this whole island to seen
count += 1
Write the rest yourself.
Debrief. The brute force searches each island again from every one of its cells: 18,000 searches of 720 cells on the speed test. Sharing one seen makes it one visit per cell, O(rows × cols). The follow-ups ask you to sink cells to "0" instead of keeping a set, and to count only islands that do not touch the border.
Measure while you search
What is the area of the largest island? A search can also report what it found: have it add 1 each time a cell comes off the stack, and return the total. Keep best, the largest size so far, starting at 0 so a map with no land answers 0.
Debrief. It is the island count with one more note per search. Two traps. Counting a cell twice: mark a cell when you push it and count it when you pop it, so each cell is counted once. Updating best in the wrong place: update it as soon as each search returns. Compare an island's size only when the next search starts, and the last island is never compared, though it can be the largest.
This module's practice bank has three more: Water to both oceans (LeetCode 417) searches backward from each ocean's edge, Clone a graph (LeetCode 133) records each copy before visiting neighbors, and Make the largest island (LeetCode 827, hard) labels every island once, then checks each water cell.
Last, say it out loud. The words you write here are the words you will use in the room.
Explain, as you would to an interviewer before typing, how you would count the islands on a map of 1s and 0s. Cover the walk, the notebook, the promise and the cost in a few plain sentences. Then answer the follow-up: "Why DFS and not BFS?"
Saved in this browser as you type.