Python 3D Academyবাংলা

Grids as graphs: islands and flood fill

🌍 In real life. A satellite photo of a coast, cut into squares: each square is land or water. How many separate islands are there, and how big is the largest? Or a paint program's bucket tool: click one square, and every touching square of the same colour changes, but nothing across a border.

No edges are written down here, yet this is a graph: every square is a vertex, joined to the squares above, below, left and right. BFS and DFS work on it unchanged; only the way to find neighbours is new.

The idea in one sentence: in a grid, each cell (r, c) is a vertex whose neighbours are the cells one step up, down, left and right that are inside the grid; an island is a connected component of land cells, and flood fill is one search that changes every cell it reaches.

Its words:

  • cell: one square, written (row, column)
  • 4-neighbours: (r − 1, c), (r + 1, c), (r, c − 1) and (r, c + 1); diagonals don't count here
  • in bounds: 0 ≤ r < rows and 0 ≤ c < cols; check it before reading a cell
  • island: a group of land cells joined through 4-neighbours
  • flood fill: starting from one cell, reach every touching cell of the same colour and paint it

How counting islands works, step by step:

  1. scan the grid row by row
  2. at a land cell no flood has reached yet: one more island
  3. flood out from it with BFS (or DFS), marking every land cell it reaches
  4. carry on scanning; marked cells are skipped

Watch three islands flood one after another, each spreading a ring at a time:

Why it is correct. Each flood is a full search from one land cell, so it marks exactly that cell's island: everything joined to it through land, and nothing across water. Every island has a first cell in scan order, and when the scan reaches it, nothing has marked it yet: a flood from an earlier island would have meant they were joined. So each island is counted exactly once. Flood fill is the same search, except that painting a cell is the mark: once a cell has the new colour, it no longer matches the old one, so it is never painted twice.

What it costs, by counting. A grid of R × C cells has R × C vertices and at most 4 neighbours each. Every cell is scanned once and every land cell is flooded once, each looking at 4 neighbours: O(R × C). For a 1,000 × 1,000 photo that is a million cells and about 4 million neighbour checks: fast, as long as no cell is ever flooded twice.

from collections import deque

def count_islands(grid):
    rows, cols = len(grid), len(grid[0])
    seen, islands = set(), 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] != "1" or (r, c) in seen:
                continue
            islands += 1                 # land no earlier flood reached: a new island
            seen.add((r, c))
            queue = deque([(r, c)])
            while queue:
                cr, cc = queue.popleft()
                for dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0)):
                    nr, nc = cr + dr, cc + dc
                    if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == "1" and (nr, nc) not in seen:
                        seen.add((nr, nc))
                        queue.append((nr, nc))
    return islands

coast = ["11000", "11010", "00011", "10000"]
print(count_islands(coast))

def flood_fill(grid, r, c, new):
    cells = [list(row) for row in grid]          # a copy: strings can't be changed in place
    old = cells[r][c]
    if old == new:
        return grid
    stack = [(r, c)]
    while stack:
        cr, cc = stack.pop()
        if not (0 <= cr < len(cells) and 0 <= cc < len(cells[0])) or cells[cr][cc] != old:
            continue
        cells[cr][cc] = new                       # paint it, which also marks it as done
        stack.extend([(cr + 1, cc), (cr - 1, cc), (cr, cc + 1), (cr, cc - 1)])
    return ["".join(row) for row in cells]

for row in flood_fill(["aab", "abb", "bba"], 0, 0, "x"):
    print(row)

Mistakes and edge cases.

  • reading outside the grid: grid[-1][c] quietly reads the last row instead of failing, and grid[rows][c] raises IndexError; check bounds first
  • counting diagonals: 4-neighbours and 8-neighbours give different islands; read which one a problem means
  • no marks: a flood visits the same cells again and again, or never ends
  • flood fill when the new colour equals the old one: painting changes nothing, so nothing is ever marked and the search loops; return early
  • changing a string in place: Python strings can't be changed; copy rows to lists, paint, and join them back

Quiz

  1. How many islands?

    from collections import deque
    
    def count_islands(grid):
        rows, cols = len(grid), len(grid[0])
        seen, islands = set(), 0
        for r in range(rows):
            for c in range(cols):
                if grid[r][c] != "1" or (r, c) in seen:
                    continue
                islands += 1                 # land no earlier flood reached: a new island
                seen.add((r, c))
                queue = deque([(r, c)])
                while queue:
                    cr, cc = queue.popleft()
                    for dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0)):
                        nr, nc = cr + dr, cc + dc
                        if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == "1" and (nr, nc) not in seen:
                            seen.add((nr, nc))
                            queue.append((nr, nc))
        return islands
    
    print(count_islands(["101", "010", "101"]))
  2. What does this print?

    def flood_fill(grid, r, c, new):
        cells = [list(row) for row in grid]          # a copy: strings can't be changed in place
        old = cells[r][c]
        if old == new:
            return grid
        stack = [(r, c)]
        while stack:
            cr, cc = stack.pop()
            if not (0 <= cr < len(cells) and 0 <= cc < len(cells[0])) or cells[cr][cc] != old:
                continue
            cells[cr][cc] = new                       # paint it, which also marks it as done
            stack.extend([(cr + 1, cc), (cr - 1, cc), (cr, cc + 1), (cr, cc - 1)])
        return ["".join(row) for row in cells]
    
    print(flood_fill(["aab", "abb", "bba"], 0, 0, "x"))
  3. A grid has 200 rows and 300 columns. About how much work is counting its islands?

    • About 60,000 cells, each with up to 4 neighbour checks: O(R × C)
    • About 60,000²
    • About 500
  4. flood_fill(["aa"], 0, 0, "a") never finishes. After which line is a check missing?

    def flood_fill(grid, r, c, new):
        cells = [list(row) for row in grid]
        old = cells[r][c]
        stack = [(r, c)]
        while stack:
            cr, cc = stack.pop()
            if not (0 <= cr < len(cells) and 0 <= cc < len(cells[0])) or cells[cr][cc] != old:
                continue
            cells[cr][cc] = new
            stack.extend([(cr + 1, cc), (cr - 1, cc), (cr, cc + 1), (cr, cc - 1)])
        return ["".join(row) for row in cells]
  5. Why must a grid search check bounds before reading grid[r][c]?

    • grid[-1] reads the last row by mistake, and grid[rows] raises IndexError
    • It makes the search find diagonals
    • It isn't needed in Python

Coding tasks

  1. Write count_islands(grid): grid is a list of equal-length strings of "1" (land) and "0" (water); return how many islands there are, joining land only up, down, left and right.

  2. Write flood_fill(grid, r, c, new): return a new grid (a list of strings) where the cell (r, c) and every cell joined to it through cells of the same character (up, down, left, right) is changed to new. Leave grid itself unchanged.

  3. Write largest_island(grid): the number of land cells in the biggest island (0 if there is no land).