4.7 Number of Islands
4.7.1 Problem Metadata
- Platform: LeetCode
- Problem ID: 200
- Difficulty: Medium
- URL: https://leetcode.com/problems/lc-number-of-islands/
- Tags: Grind 75, Blind 75, NeetCode 150
- Techniques: Depth First Search, Matrix
4.7.2 Description
Given a grid of '1' (land) and '0' (water), count the number of islands where islands are connected horizontally or vertically.
4.7.5 Solution - Flood Fill
4.7.5.1 Walkthrough
Scan every cell. Upon encountering a '1', increment the island count and perform DFS/BFS to mark the entire island as visited (turn to '0' or another marker). Continue scanning until all land is processed.
4.7.5.2 Analysis
- Time Complexity: O(rows * cols)
- Space Complexity: O(rows * cols) recursion in worst case
4.7.5.3 Implementation Steps
- Initialize
count = 0. - For each cell:
- If it is
'1', run DFS that changes it and its connected neighbors to'0', and incrementcount.
- If it is
- Return
count.
4.7.5.4 Code - Java
public int numIslands(char[][] grid) {
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++;
flood(grid, r, c);
}
}
}
return islands;
}
private void flood(char[][] grid, int r, int c) {
if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') {
return;
}
grid[r][c] = '0';
flood(grid, r - 1, c);
flood(grid, r + 1, c);
flood(grid, r, c - 1);
flood(grid, r, c + 1);
}