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.
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
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;
} def max_area_of_island(grid):
m, n = len(grid), len(grid[0])
def area(r, c): # flood fill: size of the island at (r, c)
if r < 0 or c < 0 or r >= m or c >= n or grid[r][c] != 1:
return 0
grid[r][c] = 2 # mark visited by changing the cell
return 1 + area(r + 1, c) + area(r - 1, c) + area(r, c + 1) + area(r, c - 1)
best = 0
for r in range(m):
for c in range(n):
if grid[r][c] == 1:
best = max(best, area(r, c))
return best int DIRS[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
// flood fill: the size of the island containing (r, c)
int area(vector<vector<int>>& g, int r, int c) {
if (r < 0 || c < 0 || r >= (int)g.size() || c >= (int)g[0].size() || g[r][c] != 1) return 0;
g[r][c] = 2; // mark visited by changing the cell
int total = 1;
for (auto& d : DIRS) total += area(g, r + d[0], c + d[1]);
return total;
}
int maxAreaOfIsland(vector<vector<int>>& grid) {
int best = 0;
for (int r = 0; r < (int)grid.size(); r++)
for (int c = 0; c < (int)grid[0].size(); c++)
if (grid[r][c] == 1) best = max(best, area(grid, r, c));
return best;
} const DIRS = [[1, 0], [-1, 0], [0, 1], [0, -1]];
function maxAreaOfIsland(grid) {
// flood fill: the size of the island containing (r, c)
const area = (r, c) => {
if (r < 0 || c < 0 || r >= grid.length || c >= grid[0].length || grid[r][c] !== 1) return 0;
grid[r][c] = 2; // mark visited by changing the cell
let total = 1;
for (const [dr, dc] of DIRS) total += area(r + dr, c + dc);
return total;
};
let best = 0;
for (let r = 0; r < grid.length; r++)
for (let c = 0; c < grid[0].length; c++)
if (grid[r][c] === 1) best = Math.max(best, area(r, c));
return best;
} The variations
-
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 -
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.
Now you solve -
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.
-
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.
-
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 -
6More practice
More problems that use this pattern. Try them once the variations above feel easy.
Problems- Minesweeper Medium Stuck? ▶ video
Mistakes to avoid
- Checking the bounds after reading the cell: test
randcfirst, thengrid[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.
Lesson done
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.