Graphs · Pattern 2 of 14

Grids as graphs: flood fill and islands

Every cell is a node and its 4 neighbours are its edges. A DFS from a cell floods its whole region; marking cells in the grid itself replaces the visited set.

6 variations · 9 problems · 4 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • A 2D grid of land and water, colours or walls
  • Count, measure or compare regions of connected cells
  • A ball or a player that moves by special rules on a board

The template

Matrix Graphs
int[][] DIRS = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

int maxAreaOfIsland(int[][] grid) {
    int best = 0;
    for (int r = 0; r < grid.length; r++)
        for (int c = 0; c < grid[0].length; c++)
            if (grid[r][c] == 1) best = Math.max(best, area(grid, r, c));
    return best;
}

// flood fill: the size of the island containing (r, c)
int area(int[][] g, int r, int c) {
    if (r < 0 || c < 0 || r >= g.length || c >= g[0].length || g[r][c] != 1) return 0;
    g[r][c] = 2;                                  // mark visited by changing the cell
    int total = 1;
    for (int[] d : DIRS) total += area(g, r + d[0], c + d[1]);
    return total;
}

The variations

  1. 1Flood a region

    Start a DFS at a cell and repaint every connected cell of the same value. Count the cells as you go to get an area.

    Now you solve
  2. 2Check a whole island against a rule

    Flood each island and keep one flag: "every cell is land in the other grid" (sub-islands) or "no cell touches the border" (closed islands). Visit every cell of the island before you use the flag.

  3. 3Compare island shapes

    Record each island as the path the DFS takes (the moves plus a "back" marker), or as cell offsets from its first cell. Equal shapes give equal strings, so a hash set counts the distinct ones.

  4. 4Custom moves on a board

    The nodes do not have to be every cell. A rolling ball only stops next to a wall, so the stopping cells are the nodes and each direction leads to one next stop. Search that graph with a visited set.

  5. 5Regions that grow or change

    When the region grows with a threshold, keep its border in a min-heap and absorb cells while they are small enough, answering sorted queries one after another. When it changes every day, re-find the regions each round and act on the worst one.

    Now you solve
  6. 6More practice

    More problems that use this pattern. Try them once the variations above feel easy.

    Problems

Mistakes to avoid

  • Checking the bounds after reading the cell: test r and c first, then grid[r][c].
  • Flood fill with the new colour equal to the old one: nothing changes, so the "visited" mark never sticks and the DFS loops forever. Return early.
  • Returning early from a DFS as soon as one cell fails (sub-islands, closed islands). Keep flooding the whole island, then report the result, or the leftover cells get counted as a new island later.
Next: Connected components and union-find →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.