Codiqo

Learn Java · lesson 53 of 61 · about 11 minutes

Project: Flood Fill

Fill a whole region of a grid, like the paint bucket in a drawing app, with a few lines of recursion.

What you'll learn

  • Spread from one cell to its neighbours recursively
  • Stop at the grid's edges and at walls
  • Measure regions and count them

Free seats together

Before locking up, the manager checks tomorrow's late screen: which free seats are next to each other, so groups can sit together? The seating plan is typed as rows of . for a free seat and X for a taken one. Seats joined up, down, left or right make a block, and the desk prints how many blocks there are and the size of the biggest: 2 free areas, biggest 7 seats. More than 8 rows is too many for the late screen.

The paint bucket

A picture is a grid of characters, like . for empty and # for wall. Clicking the paint bucket on a cell fills every empty cell connected to it.

That's naturally recursive. To fill from (r, c):
1. If it's off the grid, or not empty, stop: that's the base case
2. Otherwise paint it
3. Fill from the four neighbours: up, down, left and right

Filling a room

public class Main {
    static void fill(char[][] g, int r, int c) {
        if (r < 0 || r >= g.length || c < 0 || c >= g[0].length || g[r][c] != '.') return;
        g[r][c] = 'o';
        fill(g, r + 1, c);
        fill(g, r - 1, c);
        fill(g, r, c + 1);
        fill(g, r, c - 1);
    }

    public static void main(String[] args) {
        char[][] g = {
            "..#..".toCharArray(),
            "..#..".toCharArray(),
            "###..".toCharArray(),
        };
        fill(g, 0, 0);
        for (char[] row : g) System.out.println(new String(row));
    }
}

Output

oo#..
oo#..
###..

Measuring regions

If fill returns how many cells it painted (1 for itself plus whatever its neighbours painted), it measures the region. Calling it on every empty cell that's still unpainted counts how many separate regions there are.

Region size

public class Main {
    static int fill(char[][] g, int r, int c) {
        if (r < 0 || r >= g.length || c < 0 || c >= g[0].length || g[r][c] != '.') return 0;
        g[r][c] = 'o';
        return 1 + fill(g, r + 1, c) + fill(g, r - 1, c) + fill(g, r, c + 1) + fill(g, r, c - 1);
    }

    public static void main(String[] args) {
        char[][] g = {
            "..#..".toCharArray(),
            "..#..".toCharArray(),
            "###..".toCharArray(),
        };
        System.out.println(fill(g, 0, 0) + " and " + fill(g, 0, 4));
    }
}

Output

4 and 6

Rows of different lengths

A typed row can be shorter or longer than the others, so freeBlock checks c >= plan[r].length against the row it's on, not plan[0].length. It checks r first: || stops at the first true part, so plan[r] is only read once r is known to be on the plan.

Tip

Painting the cell before recursing matters: it marks the cell as visited, so the neighbours don't send the fill straight back to it forever.

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.