iq.lab
Python starts when a code cell comes near or you run one
10 Graphs

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.

About 1 hour 45 minutes, with the 3 problems worked in it
By the end you can
  • 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:

NodeNeighbors
AB, C
BA, D
CA, D
DB, C, E
ED

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.

Step throughDepth-first from A
Step 1 of 51
Line 1 is about to run.
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)
Names
no names yet
Output
(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.

PredictWho comes last?

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.

Quick checkA search with no notebook

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.

Code itEverything you can reach

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.

⌘+Enter runsPython starts when a code cell comes near or you run one
Write your code where the starter says 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.

Step throughPainting a region, one call per cell
Step 1 of 102
Line 1 is about to run.
image = [[1, 1, 0], [1, 1, 0], [0, 1, 1]]
rows, cols = 3, 3
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] # down, up, right, left
def paint(r, c):
image[r][c] = 5
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and image[nr][nc] == 1:
paint(nr, nc)
paint(0, 0)
print(image)
Names
no names yet
Output
(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 in orderThe painter, in order

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.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • def fill(image, r, c, old, color):
    • nr, nc = r + dr, c + dc
    • image[r][c] = color
    • if 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.

    Work it outCounting the calls

    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?

    calls

    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.

    Step throughThe same search with a stack of your own
    Step 1 of 109
    Line 1 is about to run.
    def explore(grid, start):
    rows, cols = len(grid), len(grid[0])
    directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] # down, up, right, left
    seen = {start}
    stack = [start]
    while stack:
    r, c = stack.pop()
    for dr, dc in directions:
    nr, nc = r + dr, c + dc
    if 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)
    Names
    no names yet
    Output
    (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.

    On paperRun the stack 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.

    visit number of (1, 0)

    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.

    easyDepth-first search target 15 min

    Flood fill

    image is a grid of pixels, a list of rows, and image[r][c] is the color of the pixel in row r and column c, stored as a whole number. You also get a starting pixel at row row and column col, and a new color.

    Paint the region of the starting pixel with color. The region is the starting pixel plus every pixel you can reach from it by stepping up, down, left or right (not diagonally), only through pixels that have the starting pixel's original color. Pixels outside the region keep their color.

    Return the painted grid. You may change image in place and return it.

    Example 1
    Inputimage = [[1, 1, 0], [0, 1, 0], [1, 0, 1]], row = 0, col = 0, color = 5Output[[5, 5, 0], [0, 5, 0], [1, 0, 1]]

    The three 1s joined by sides become 5. The 1s in the bottom corners touch the region only at a corner, so they stay 1.

    Example 2
    Inputimage = [[0, 0, 0], [0, 7, 7], [0, 7, 0]], row = 2, col = 2, color = 4Output[[0, 0, 0], [0, 7, 7], [0, 7, 4]]

    The 0 in the bottom-right corner is walled in by 7s, so its region is that one pixel. The other 0s are not connected to it.

    Example 3
    Inputimage = [[3, 3], [3, 1]], row = 0, col = 0, color = 3Output[[3, 3], [3, 1]]

    The new color is the old color, so nothing changes.

    Constraints
    • 1 ≤ number of rows, number of columns ≤ 50

    • Colors, in the image and in color, are whole numbers from 0 to 65,535.

    • 0 ≤ row < number of rows and 0 ≤ col < number of columns

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    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.

    Step throughOne search per group
    Step 1 of 58
    Line 1 is about to run.
    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 = 0
    for node in graph:
    if node not in seen:
    dfs(node)
    count += 1
    print(count)
    Names
    no names yet
    Output
    (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.

    Work it outCount the 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
    
    islands

    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.

    mediumDepth-first search target 25 min

    Number of islands

    A map is a grid of strings: "1" is land and "0" is water. Two land cells are on the same island when you can walk from one to the other by stepping up, down, left or right, only on land. Diagonal steps do not count. Everything outside the grid is water.

    Return how many islands the map holds.

    The cells are the strings "1" and "0", not the numbers 1 and 0, the same as on LeetCode. Compare with "1".

    Example 1
    Inputgrid = [["1", "1", "0", "0"], ["0", "1", "0", "1"], ["1", "0", "0", "1"]]Output3

    The three land cells at the top left, the two on the right, and the single cell at the bottom left.

    Example 2
    Inputgrid = [["1", "0", "1"], ["0", "1", "0"], ["1", "0", "1"]]Output5

    Each land cell touches the others only at corners, so each one is its own island.

    Example 3
    Inputgrid = [["0", "0"], ["0", "0"]]Output0

    No land, no islands.

    Constraints
    • 1 ≤ number of rows, number of columns ≤ 300

    • Every cell is "0" or "1".

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    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.

    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.

    mediumDepth-first search target 25 min

    Largest island

    A map is a grid of numbers: 1 is land and 0 is water. Two land cells are on the same island when you can walk from one to the other by stepping up, down, left or right, only on land. Diagonal steps do not count. An island's area is how many land cells it holds.

    Return the largest area of any island, or 0 if the map has no land.

    Example 1
    Inputgrid = [[1, 1, 0, 0], [0, 1, 0, 1], [1, 0, 1, 1], [0, 0, 1, 0]]Output4

    Writing cells as (row, column), the island on the right is (1, 3), (2, 3), (2, 2) and (3, 2): area 4. The island at the top left has area 3, and (2, 0) alone has area 1.

    Example 2
    Inputgrid = [[0, 0], [0, 0]]Output0

    There is no land, so there is no island.

    Example 3
    Inputgrid = [[1, 0, 1, 1, 1]]Output3

    The three 1s at the end form the largest island.

    Constraints
    • 1 ≤ number of rows, number of columns ≤ 50

    • Every cell is 0 or 1.

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    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.

    Say itSay it like you would 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?"

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: Breadth-first search