Kodewick
Start learning →
Patterns: graphs36 / 52

Patterns: graphs

Lesson 36 of 52 · Part 6 · Graphs · about 22 minutes

This chapter 5 review covers three graph patterns: flood-filling a grid to count islands, two-colouring with BFS to test whether a graph is bipartite, and multi-source BFS for each cell's distance to the nearest source, all O(n + e).

Graph problems seem to come in every shape: number of islands, surrounded regions, rotting oranges, walls and gates, is the graph bipartite, possible bipartition, distance to the nearest 0… Most need no new algorithm, only BFS and DFS in another guise. This lesson covers the three patterns asked most: a grid is a graph, so fill from each patch of land not yet visited and the number of fills is the number of islands; colour neighbours differently as BFS walks, and if the colouring fails the graph is not bipartite; and for "how far to the nearest source", put every source at once into the queue and one BFS works everything out. All three are O(n + e), which on a grid is O(R × C).

Pattern 1: counting islands on a grid

"1" is land, "0" is water, and land cells next to each other up, down, left or right make one island (touching diagonally doesn't count). To count the islands, scan from the top left to the bottom right; at a land cell not yet visited, add one island and run a BFS (or DFS) from it that marks all the land joined to it as visited. This is the last lesson's "count connected components", with the neighbours swapped for the four cells around, and it is called flood fill.

01234011000111011200010310000

Each unvisited land cell the scan reaches starts a new island, and BFS gives all the land joined to it the same letter; at the end of the scan there are 3
main.py
1from collections import deque2 3def num_islands(grid):4    rows, cols = len(grid), len(grid[0])5    seen = set()6    count = 07    for r in range(rows):8        for c in range(cols):9            if grid[r][c] == "1" and (r, c) not in seen:10                count += 1                       # a new island11                seen.add((r, c))12                q = deque([(r, c)])13                while q:                         # fill this island14                    x, y = q.popleft()15                    for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):16                        nx, ny = x + dx, y + dy17                        if 0 <= nx < rows and 0 <= ny < cols and grid[nx][ny] == "1" and (nx, ny) not in seen:18                            seen.add((nx, ny))19                            q.append((nx, ny))20    return count21 22grid = [23    "11000",24    "11011",25    "00010",26    "10000",27]28print(num_islands(grid))29print(num_islands(["111", "111"]), num_islands(["000"]), num_islands(["101", "010", "101"]))
Output
3
1 0 5

The fill can be BFS or DFS, but not recursive DFS: a 300 × 300 map of solid land would stack 90,000 calls, the RecursionError of lesson 3. BFS or an explicit stack has no such problem.

Common variations: how big is the largest island (count cells while filling, this stage's exercise), the island's perimeter, regions surrounded by water (fill from the land on the edges first; what is left is surrounded).

Choose one

1 is land and 0 is water. Counting only up, down, left and right as connected, how many islands does this grid have?

11 0 120 1 031 0 1
Exercise 1

The largest island

Complete max_area(grid): in grid, 1 is land and 0 is water; return how many cells the largest island has, or 0 if there is no land. Use an explicit stack or BFS, not recursion.

It should print
5
0
1
exercise1.py
1def max_area(grid):2    rows, cols = len(grid), len(grid[0])3    seen = set()4    best = 05    # for each unvisited land cell: start a stack, count a cell per pop, push unvisited land in the four directions6    return best7 8grid = [9    [0, 0, 1, 0, 0],10    [1, 1, 1, 0, 1],11    [0, 1, 0, 0, 1],12    [0, 0, 0, 1, 1],13]14print(max_area(grid))15print(max_area([[0, 0], [0, 0]]))16print(max_area([[1, 0, 1]]))
Output
Press Run or Ctrl+Enter

Pattern 2: the two-colour test for bipartite graphs

A bipartite graph is one whose vertices split into two groups with every edge joining vertices from different groups: "students and courses", "applicants and jobs". The test is to paint two colours: in BFS the start gets 0, its neighbours 1, their neighbours 0, and so on; an edge with the same colour at both ends means it is not bipartite.

A graph is bipartite exactly when it has no cycle with an odd number of edges: go round a triangle and the colours run 0, 1, 0, so back at the start it should be 1, but it is already 0.

The number on a vertex is its colour: 0's neighbours all get 1; when 1 leaves the queue it finds its neighbour 2 is also 1, an edge with the same colour at both ends, so the graph is not bipartite
main.py
1from collections import deque2 3def is_bipartite(graph):4    color = [-1] * len(graph)                    # -1 = no colour yet5    for s in range(len(graph)):                  # the graph may be in pieces: colour each one6        if color[s] != -1:7            continue8        color[s] = 09        q = deque([s])10        while q:11            u = q.popleft()12            for v in graph[u]:13                if color[v] == -1:14                    color[v] = 1 - color[u]      # the other colour15                    q.append(v)16                elif color[v] == color[u]:17                    return False, color          # an edge with the same colour at both ends18    return True, color19 20print(is_bipartite([[1, 2, 3], [0, 2], [0, 1, 3], [0, 2]]))21print(is_bipartite([[1, 3], [0, 2], [1, 3], [0, 2]]))22print(is_bipartite([[1], [0], [3], [2]]))
Output
(False, [0, 1, 1, 1])
(True, [0, 1, 0, 1])
(True, [0, 1, 0, 1])

The second graph is a square (an even cycle), coloured 0, 1, 0, 1 with no trouble; the third falls into two separate pieces, which is why the outer for s in range(...) can't be left out: starting only from 0, 2 and 3 would never be coloured.

VariationHow it is a bipartite graph
Possible bipartition (people who dislike each other in two groups)dislikes are edges; can it be painted in two colours?
Can they split into two teams?the same; if the colouring fails, they can't
Maximum bipartite matching (applicants and jobs)confirm it is bipartite first, then the Hungarian algorithm (beyond this course)
Choose one

Which of these graphs is bipartite?

Exercise 2

Can they split into two groups?

Complete can_split(n, dislikes): n people are numbered 0 to n − 1, and (a, b) in dislikes means a and b dislike each other and can't be in the same group. Return True if they can split into two groups. Build the adjacency list first, then paint two colours with BFS; the graph may be in pieces.

It should print
True
False
False
True
exercise2.py
1from collections import deque2 3def can_split(n, dislikes):4    graph = [[] for _ in range(n)]5    for a, b in dislikes:6        graph[a].append(b)7        graph[b].append(a)8    color = [-1] * n9    # one BFS per person without a colour: neighbours get 1 - color[u]; the same colour returns False10    return True11 12print(can_split(4, [(0, 1), (0, 2), (1, 3)]))13print(can_split(3, [(0, 1), (0, 2), (1, 2)]))14print(can_split(5, [(0, 1), (2, 3), (3, 4), (4, 2)]))15print(can_split(3, []))
Output
Press Run or Ctrl+Enter

Pattern 3: multi-source BFS

Rotting oranges: 2 is a rotten orange, 1 a fresh one, 0 an empty cell. Every minute, a rotten orange turns the fresh oranges above, below, left and right of it rotten. What is the fewest minutes until all are rotten, or -1 if some fresh orange can never be reached?

A separate BFS from each rotten orange means k runs for k rotten oranges, O(k × R × C). Multi-source BFS: at the start, put every rotten orange in the queue together, all at distance 0. The BFS spreads out layer by layer, one layer per minute; the first time a fresh orange is reached, it is reached from the rotten orange closest to it. One BFS, O(R × C).

0123400FF·F1FF·FF2·FFF0

Both rotten oranges (0) join the queue together: the number in a cell is the minute it rots, · is an empty cell; the last one rots in minute 3
main.py
1from collections import deque2 3def oranges_rotting(grid):4    grid = [row[:] for row in grid]              # leave the caller's list alone5    rows, cols = len(grid), len(grid[0])6    q = deque()7    fresh = 08    for r in range(rows):9        for c in range(cols):10            if grid[r][c] == 2:11                q.append((r, c, 0))              # every source joins together12            elif grid[r][c] == 1:13                fresh += 114    minutes = 015    while q:16        r, c, t = q.popleft()17        minutes = max(minutes, t)18        for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):19            nr, nc = r + dr, c + dc20            if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1:21                grid[nr][nc] = 2                 # changing it to 2 is the mark22                fresh -= 123                q.append((nr, nc, t + 1))24    return minutes if fresh == 0 else -125 26print(oranges_rotting([[2, 1, 1, 0, 1], [1, 1, 0, 1, 1], [0, 1, 1, 1, 2]]))27print(oranges_rotting([[2, 1, 1], [0, 1, 1], [1, 0, 1]]))28print(oranges_rotting([[0, 2]]))
Output
3
-1
0

In the second example, the 1 in the bottom-left corner has only empty cells and edges around it and can never rot, so the answer is -1. There is no separate seen here: changing a fresh orange to 2 is the mark, and it too is done on enqueue.

The same pattern also solves: each cell's distance to the nearest 0 (this stage's exercise), walls and gates (each room's distance to the nearest gate), the distance to the nearest hospital on a map. What they share: "many starting points, how far to the nearest one".

PatternHow to spot itWhat to doTime
Islands / connected pieces"how many pieces", "the largest piece"one BFS / explicit stack per unvisited cellO(R × C)
Bipartite"two groups, no edge inside a group"BFS painting two colours; same colour next to each other failsO(n + e)
Multi-source BFS"how far to the nearest", "spreading at the same time"every source in the queue together, at distance 0O(R × C) or O(n + e)
Single-source BFS"fewest steps from here to there"lesson 2O(n + e)

In interviews: for a grid problem, first say "a grid is a graph, each cell has at most four neighbours", then pick the pattern. Three easy mistakes: the bounds check goes before reading the cell; mark on enqueue; no recursion for the fill (a large grid raises RecursionError). Asked whether it can be done without extra space: yes, by changing visited cells in place ("1" to "0", fresh oranges to 2), but ask first whether the input may be changed.

Choose one

A row of 7 cells, rotten oranges at both ends and 5 fresh ones between: 2 1 1 1 1 1 2. How many minutes until all are rotten?

Exercise 3

Distance to the nearest 0

Complete nearest_zero(mat): mat holds only 0s and 1s; return a table of the same size where each cell is how many steps it is from the nearest 0 (up, down, left and right only). Use multi-source BFS: all the 0s join the queue together.

It should print
[0, 0, 0]
[0, 1, 0]
[1, 2, 1]
[3, 2, 1, 2]
[2, 1, 0, 1]
[3, 2, 1, 2]
exercise3.py
1from collections import deque2 3def nearest_zero(mat):4    rows, cols = len(mat), len(mat[0])5    dist = [[-1] * cols for _ in range(rows)]    # -1 = not reached yet6    q = deque()7    # every 0: dist is 0 and it joins the queue; then BFS with dist[nr][nc] = dist[r][c] + 18    return dist9 10for row in nearest_zero([[0, 0, 0], [0, 1, 0], [1, 1, 1]]):11    print(row)12for row in nearest_zero([[1, 1, 1, 1], [1, 1, 0, 1], [1, 1, 1, 1]]):13    print(row)
Output
Press Run or Ctrl+Enter

How you write it at work

These three patterns turn up at work too: the "paint bucket" in image editing is flood fill; splitting tasks that conflict onto two machines is the bipartite test; working out each neighbourhood's nearest warehouse, starting from several warehouses at once, is multi-source BFS. All they use is collections.deque. A few small habits for grid problems:

  • Write the four directions once as a module-level constant DIRS = ((-1, 0), (1, 0), (0, -1), (0, 1)); for eight directions, add the four diagonals.
  • A grid of strings can't be changed (str is immutable): to mark in place, first grid = [list(row) for row in grid].
  • Put coordinates in a set as tuples (r, c); or pack them into one number, r * cols + c.
main.py
1from collections import deque2 3DIRS = ((-1, 0), (1, 0), (0, -1), (0, 1))4 5def fill(image, r, c, new):6    image = [row[:] for row in image]7    old = image[r][c]8    if old == new:9        return image10    rows, cols = len(image), len(image[0])11    image[r][c] = new                            # changing the colour is the mark12    q = deque([(r, c)])13    while q:14        x, y = q.popleft()15        for dx, dy in DIRS:16            nx, ny = x + dx, y + dy17            if 0 <= nx < rows and 0 <= ny < cols and image[nx][ny] == old:18                image[nx][ny] = new19                q.append((nx, ny))20    return image21 22image = [[1, 1, 1], [1, 1, 0], [1, 0, 1]]23for row in fill(image, 1, 1, 2):24    print(row)
Output
[2, 2, 2]
[2, 2, 0]
[2, 0, 1]

The 1 in the bottom-right corner only touches diagonally and is not filled: exactly what a paint bucket does.

Guess the outputA wrong guess is fine

Paint bucket: start at the top-right corner (0, 2) and change every connected b to c. What does this print?

1from collections import deque2 3def fill(image, r, c, new):4    old = image[r][c]5    image[r][c] = new6    q = deque([(r, c)])7    count = 18    while q:9        x, y = q.popleft()10        for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):11            nx, ny = x + dx, y + dy12            if 0 <= nx < len(image) and 0 <= ny < len(image[0]) and image[nx][ny] == old:13                image[nx][ny] = new14                q.append((nx, ny))15                count += 116    return count17 18image = [list("aab"), list("abb"), list("bab")]19print(fill(image, 0, 2, "c"), "".join(image[2]))

Summary

Take-away

Three graph patterns

  • Islands: one BFS / explicit stack per unvisited land cell; the number of runs is the number of islands
  • Bipartite: BFS paints two colours, a neighbour gets 1 - color[u]; same colours next to each other (an odd cycle) means no
  • Multi-source BFS: every source in the queue together at distance 0; one pass gives the distance to the nearest
  • Grids: a tuple of four directions, bounds before the cell, mark on enqueue, no recursion
1DIRS = ((-1, 0), (1, 0), (0, -1), (0, 1))2q = deque(sources)          # every source at once3while q:4    r, c = q.popleft()5    for dr, dc in DIRS: ...

Chapter 5 quick check

5 questions: building a graph plus BFS, DFS with an explicit stack, topological sort, Dijkstra's lazy deletion, and Kruskal. Work out what each prints first, then pick an option.

Guess the outputA wrong guess is fine

An undirected graph is built from an edge list, then BFS runs from 0. What does it print?

1from collections import defaultdict, deque2 3edges = [(0, 1), (0, 2), (1, 3), (2, 3), (3, 4)]4graph = defaultdict(list)5for u, v in edges:6    graph[u].append(v)7    graph[v].append(u)8dist = {0: 0}9q = deque([0])10while q:11    u = q.popleft()12    for v in graph[u]:13        if v not in dist:14            dist[v] = dist[u] + 115            q.append(v)16print(dist[4], len(graph[3]))
Guess the outputA wrong guess is fine

DFS with an explicit stack, neighbours pushed in stored order. What does it print?

1graph = {1: [2, 3], 2: [4], 3: [4], 4: []}2seen = set()3stack = [1]4order = []5while stack:6    u = stack.pop()7    if u in seen:8        continue9    seen.add(u)10    order.append(u)11    for v in graph[u]:12        if v not in seen:13            stack.append(v)14print(order)
Guess the outputA wrong guess is fine

Kahn's algorithm. What does it print?

1from collections import deque2 3edges = [(3, 1), (1, 0), (2, 0), (3, 2)]4n = 45graph = [[] for _ in range(n)]6indeg = [0] * n7for u, v in edges:8    graph[u].append(v)9    indeg[v] += 110q = deque(i for i in range(n) if indeg[i] == 0)11order = []12while q:13    u = q.popleft()14    order.append(u)15    for v in graph[u]:16        indeg[v] -= 117        if indeg[v] == 0:18            q.append(v)19print(order)
Guess the outputA wrong guess is fine

Dijkstra, with stale heap entries skipped when they pop. What does it print?

1import heapq2 3graph = {"A": {"B": 1, "C": 4}, "B": {"C": 2, "D": 6}, "C": {"D": 1}, "D": {}}4dist = {"A": 0}5heap = [(0, "A")]6skipped = 07while heap:8    d, u = heapq.heappop(heap)9    if d > dist[u]:10        skipped += 111        continue12    for v, w in graph[u].items():13        if v not in dist or d + w < dist[v]:14            dist[v] = d + w15            heapq.heappush(heap, (d + w, v))16print(dist["D"], skipped)
Guess the outputA wrong guess is fine

Edges stored as (weight, u, v), Kruskal with union-find. What does it print?

1edges = [(1, 0, 1), (4, 0, 2), (3, 1, 2), (2, 2, 3), (5, 1, 3)]2parent = list(range(4))3 4def find(x):5    while parent[x] != x:6        x = parent[x]7    return x8 9total = 010for w, u, v in sorted(edges):11    ru, rv = find(u), find(v)12    if ru != rv:13        parent[rv] = ru14        total += w15print(total)