Number of Islands
Medium · Graphs
Jump to codeCount connected groups of land in a rectangular grid of 0s and 1s. Land connects horizontally or vertically, never diagonally.
Examples
Example 1
grid = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]
Output: 1
Example 2
grid = [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]
Output: 3
Constraints
- 1 <= grid.length, grid[i].length <= 100
- grid[i][j] is '0' or '1'.
Need a hint?
Each unseen land cell begins one component.
Asked in real interviews
Candidates reported versions of Number of Islands from these company interviews. Some company questions are locked and open with Premium or XP.
- Count Islands in a Grid and Track the Count as Land Cells Are AddedGoogle
- Count Islands in a Binary GridApple
- Count islands with eight-direction adjacencySnapchat
Solution approach
Scan the grid. When a cell is land and unvisited, increase the answer and flood-fill all land reachable from it using a stack or queue. Mark cells when enqueuing to prevent repeated work. Keep a visited set if the input must remain unchanged.
Complexity
O(mn) time and O(mn) worst-case space.
Python reference solution
def numIslands(grid):
rows, cols = len(grid), len(grid[0]) if grid else 0
count = 0
for row in range(rows):
for col in range(cols):
if grid[row][col] != '1':
continue
count += 1
grid[row][col] = '0'
stack = [(row, col)]
while stack:
r, c = stack.pop()
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == '1':
grid[nr][nc] = '0'
stack.append((nr, nc))
return count
JavaScript solution
function numIslands(grid) {
const rows = grid.length, cols = rows ? grid[0].length : 0;
const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]];
let count = 0;
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
if (grid[row][col] !== '1') continue;
count++;
grid[row][col] = '0';
const stack = [[row, col]];
while (stack.length) {
const [r, c] = stack.pop();
for (const [dr, dc] of directions) {
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] === '1') {
grid[nr][nc] = '0';
stack.push([nr, nc]);
}
}
}
}
}
return count;
}
Java solution
import java.util.*;
class Solution {
public int numIslands(char[][] grid) {
int rows = grid.length, cols = rows == 0 ? 0 : grid[0].length, count = 0;
int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
if (grid[row][col] != '1') continue;
count++;
grid[row][col] = '0';
Deque<int[]> stack = new ArrayDeque<>();
stack.push(new int[]{row, col});
while (!stack.isEmpty()) {
int[] cell = stack.pop();
for (int[] d : directions) {
int r = cell[0] + d[0], c = cell[1] + d[1];
if (r >= 0 && r < rows && c >= 0 && c < cols && grid[r][c] == '1') {
grid[r][c] = '0';
stack.push(new int[]{r, c});
}
}
}
}
}
return count;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int numIslands(vector<vector<char>> &grid) {
int rows = grid.size(), cols = rows ? grid[0].size() : 0, count = 0;
vector<pair<int, int>> directions{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
if (grid[row][col] != '1') continue;
count++;
grid[row][col] = '0';
vector<pair<int, int>> pending{{row, col}};
while (!pending.empty()) {
auto [r, c] = pending.back(); pending.pop_back();
for (auto [dr, dc] : directions) {
int nr = r + dr, nc = c + dc;
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] == '1') {
grid[nr][nc] = '0';
pending.push_back({nr, nc});
}
}
}
}
}
return count;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 11 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
[
"1",
"1",
"1",
"1",
"0"
],
[
"1",
"1",
"0",
"1",
"0"
],
[
"1",
"1",
"0",
"0",
"0"
],
[
"0",
"0",
"0",
"0",
"0"
]
]
]1
[
[
[
"1",
"1",
"0",
"0",
"0"
],
[
"1",
"1",
"0",
"0",
"0"
],
[
"0",
"0",
"1",
"0",
"0"
],
[
"0",
"0",
"0",
"1",
"1"
]
]
]3
[
[
[
"0",
"0",
"0"
],
[
"0",
"0",
"0"
]
]
]0
[
[
[
"1",
"0",
"1",
"0",
"1"
]
]
]3
[
[
[]
]
]0
Drafts are saved per language in this browser when storage is available.