IntermediateGraphs

A grid is a graph: counting islands with DFS

Each cell is a joined to its 4 neighbours. Every time you find unvisited land, flood it with and count one island.

The idea

You don't need to build a for a grid: a cell's neighbours are just up, down, left and right. Walk every cell; when you hit land you haven't visited, that's a new island. Flood-fill from it so the rest of that island is marked and never counted again.

Marking can be done (turn '1' into '0'), so no extra is needed.

Worked example

Grid rows: 1 1 0 / 0 1 0 / 0 0 1

  1. (0,0) is land → island 1 → flood (0,0), (0,1), (1,1)
  2. (2,2) is land and unvisited → island 2
  3. Answer 2.

In code (Python)

def num_islands(grid):
    rows, cols = len(grid), len(grid[0])

    def flood(r, c):
        if r < 0 or c < 0 or r >= rows or c >= cols or grid[r][c] != "1":
            return
        grid[r][c] = "0"                 # visited
        flood(r + 1, c); flood(r - 1, c); flood(r, c + 1); flood(r, c - 1)

    islands = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == "1":
                islands += 1
                flood(r, c)
    return islands

O(rows × cols) time; up to the island size.

How to spot it

  • “islands”, “regions”, “connected areas”, “”, anything over a 2-D grid of cells.

Common mistakes

  • Checking bounds after indexing, which crashes at the .
  • Forgetting to mark cells, so DFS loops forever between two neighbours.

Practise the ideas first

Practise it

Go further