1. DFS Flood Fill (In-Place Sink)
OptimalScan every cell in the grid. Upon finding an unvisited land cell ('1'), increment the island count and recursively sink all horizontally and vertically connected land cells to '0'.
Every cell in the M x N grid is visited at most a constant number of times (once by the outer nested loop, and once by the DFS recursive sink).
In the worst case where the entire grid is land (all '1's), the recursion stack reaches depth M x N.
How It Works
The Connected Component Mental Model
In graph theory, a 2D grid of land and water is an undirected graph where:
- Each land cell
'1'is a vertex. - Adjacent horizontal and vertical land cells share an edge.
- An "island" is a connected component.
The Sinking Technique:
To avoid allocating an m x n auxiliary visited boolean matrix, we can "sink" visited land directly by mutating grid[r][c] = '0':
- Iterate over every row
rfrom0tom - 1and columncfrom0ton - 1. - When we encounter
grid[r][c] == '1':
- We have discovered a brand new unvisited island!
- Increment our total
islandCount++. - Trigger a DFS flood-fill starting at
(r, c)to sink this entire island so we never double-count it.
- In the DFS function:
- Check boundary guards: if
r < 0,r >= m,c < 0,c >= n, orgrid[r][c] == '0', return immediately. - Sink the current cell:
grid[r][c] = '0'. - Recursively call DFS in all 4 cardinal directions:
- Up:
(r - 1, c) - Down:
(r + 1, c) - Left:
(r, c - 1) - Right:
(r, c + 1)
- Return
islandCount.
Step-by-Step Dry Run
Inspect (0, 0) = '1'. Island count = 1. Trigger DFS flood fill to sink connected landmass.
islands = 1DFS expanding from (0, 0)- +Zero auxiliary space overhead for a visited matrix (mutates grid in-place)
- +Concise 4-directional flood fill logic
- -Mutates original grid data
- -Deep recursion risk on dense 300x300 grids if call stack is small
Reference Implementation
Complete implementation for DFS Flood Fill (In-Place Sink) in Python, JavaScript, Java, C++, and C.
def num_islands(grid: list[list[str]]) -> int:if not grid or not grid[0]:return 0rows, cols = len(grid), len(grid[0])islands = 0def dfs(r: int, c: int) -> None:if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != "1":returngrid[r][c] = "0" # sink landdfs(r + 1, c)dfs(r - 1, c)dfs(r, c + 1)dfs(r, c - 1)for r in range(rows):for c in range(cols):if grid[r][c] == "1":islands += 1dfs(r, c)return islandsif __name__ == "__main__":grid = [["1", "1", "0", "0", "0"],["1", "1", "0", "0", "0"],["0", "0", "1", "0", "0"],["0", "0", "0", "1", "1"]]print("Number of islands:", num_islands(grid))
function numIslands(grid) {
if (!grid || grid.length === 0) return 0;
const rows = grid.length;
const cols = grid[0].length;
let count = 0;
function dfs(r, c) {
if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] !== "1") {
return;
}
grid[r][c] = "0"; // sink land
dfs(r + 1, c);
dfs(r - 1, c);
dfs(r, c + 1);
dfs(r, c - 1);
}
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (grid[r][c] === "1") {
count++;
dfs(r, c);
}
}
}
return count;
}
const grid = [
["1", "1", "0", "0", "0"],
["1", "1", "0", "0", "0"],
["0", "0", "1", "0", "0"],
["0", "0", "0", "1", "1"]
];
console.log("Islands:", numIslands(grid));public class Solution {
public static int numIslands(char[][] grid) {
if (grid == null || grid.length == 0) {
return 0;
}
int rows = grid.length;
int cols = grid[0].length;
int islands = 0;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (grid[r][c] == '1') {
islands++;
dfs(grid, r, c, rows, cols);
}
}
}
return islands;
}
private static void dfs(char[][] grid, int r, int c, int rows, int cols) {
if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] != '1') {
return;
}
grid[r][c] = '0'; // sink land
dfs(grid, r + 1, c, rows, cols);
dfs(grid, r - 1, c, rows, cols);
dfs(grid, r, c + 1, rows, cols);
dfs(grid, r, c - 1, rows, cols);
}
public static void main(String[] args) {
char[][] grid = {
{'1', '1', '0', '0', '0'},
{'1', '1', '0', '0', '0'},
{'0', '0', '1', '0', '0'},
{'0', '0', '0', '1', '1'}
};
System.out.println("Islands: " + numIslands(grid));
}
}#include <iostream>
#include <vector>
void dfs(std::vector<std::vector<char>>& grid, int r, int c, int rows, int cols) {
if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] != '1') {
return;
}
grid[r][c] = '0'; // sink land
dfs(grid, r + 1, c, rows, cols);
dfs(grid, r - 1, c, rows, cols);
dfs(grid, r, c + 1, rows, cols);
dfs(grid, r, c - 1, rows, cols);
}
int numIslands(std::vector<std::vector<char>>& grid) {
if (grid.empty()) return 0;
int rows = grid.size();
int cols = grid[0].size();
int islands = 0;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (grid[r][c] == '1') {
islands++;
dfs(grid, r, c, rows, cols);
}
}
}
return islands;
}
int main() {
std::vector<std::vector<char>> grid = {
{'1', '1', '0', '0', '0'},
{'1', '1', '0', '0', '0'},
{'0', '0', '1', '0', '0'},
{'0', '0', '0', '1', '1'}
};
std::cout << "Islands: " << numIslands(grid) << "\n";
return 0;
}#include <stdio.h>
void dfs(char grid[4][5], int r, int c, int rows, int cols) {
if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] != '1') {
return;
}
grid[r][c] = '0'; // sink land
dfs(grid, r + 1, c, rows, cols);
dfs(grid, r - 1, c, rows, cols);
dfs(grid, r, c + 1, rows, cols);
dfs(grid, r, c - 1, rows, cols);
}
int numIslands(char grid[4][5], int rows, int cols) {
int islands = 0;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (grid[r][c] == '1') {
islands++;
dfs(grid, r, c, rows, cols);
}
}
}
return islands;
}
int main(void) {
char grid[4][5] = {
{'1', '1', '0', '0', '0'},
{'1', '1', '0', '0', '0'},
{'0', '0', '1', '0', '0'},
{'0', '0', '0', '1', '1'}
};
printf("Islands: %d\n", numIslands(grid, 4, 5));
return 0;
}