Number of Islands
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
You're given an m x n grid of "1" (land) and "0" (water). Return the number of islands.
Understand the problem
- An island is a group of land cells that are connected horizontally or vertically (up, down, left, right). Diagonal doesn't count.
- Everything outside the grid is water.
- You're counting groups, not land cells: a big island of 10 cells still counts as 1.
Example 1
Input:
[["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]]
Output: 1All the land cells touch each other, so it's one island.
Example 2
Input:
[["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]]
Output: 3The top-left block of four, the single 1 in the middle, and the pair at the bottom right. The middle 1 and the bottom-right pair only touch diagonally, so they're separate islands.
Constraints
1 <= m, n <= 300grid[i][j]is"0"or"1".
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
Scan the grid; every time you find land, count a new island and "sink" all the land connected to it, so it's never counted again.
A grid is a graph
A graph is a set of things (nodes) with connections between them (edges). A grid is a graph in disguise:
- every land cell is a node;
- two land cells that are next to each other (up, down, left, right) are connected by an edge.
An island is then a group of nodes all reachable from one another: a connected component. Counting islands means counting connected components.
The key insight: flood fill
Scan the grid row by row. When you hit a "1":
- It's a new island (if it belonged to an island we'd already counted, it would have been sunk). Add 1 to the count.
- Sink the whole island: visit every land cell connected to it and set each one to
"0". This is a flood fill, like the paint-bucket tool in a drawing app.
Because the whole island disappears at once, the rest of the scan only finds land belonging to other islands.
To visit the connected cells, use a stack: push the starting cell; then repeatedly pop a cell and push each neighbor that's still land, marking it "0" immediately (so it's never pushed twice). This is a depth-first search (DFS).
Step by step
Example 2:
| Scan reaches | Cell is | What happens | Count |
|---|---|---|---|
| (0, 0) | "1" | new island! sink (0,0), (0,1), (1,0), (1,1) | 1 |
| (0, 1) … (2, 1) | "0" | water (or already sunk): skip | 1 |
| (2, 2) | "1" | new island! sink it: its neighbors are all water | 2 |
| (3, 3) | "1" | new island! sink (3,3) and (3,4) | 3 |
| (3, 4) | "0" | already sunk: skip | 3 |
Answer: 3.
The code
The reference solution is below, with comments on every important line.
How fast is it?
- Time: O(m · n). Each cell is scanned once and sunk at most once.
- Memory: O(m · n) in the worst case for the stack (a grid that's all land).
Common mistakes
- Counting land cells instead of islands. Without sinking, every
"1"would add to the count. - Marking a cell visited when you pop it instead of when you push it. A cell can then be pushed several times by different neighbors. Correct, but wasteful.
- Including diagonal neighbors. Only 4 directions.
- Deep recursion. A recursive DFS on a 300×300 snake-shaped island can go 90,000 calls deep and overflow the call stack. An explicit stack avoids that.
Going deeper
- BFS with a queue works just as well for the flood fill.
- If you can't modify the input, keep a separate
visitedgrid instead of writing"0". - The same "count the connected components" idea appears in Number of Connected Components in an Undirected Graph, where the graph is given as a list of edges instead of a grid.
Reference solution
/**
* @param {string[][]} grid
* @return {number}
*/
export default function numIslands(grid) {
const rows = grid.length
const cols = grid[0].length
let count = 0
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (grid[r][c] !== '1') continue // water, or land we already sank
// Unvisited land: a new island. Count it, then sink all of it.
count++
grid[r][c] = '0'
const stack = [[r, c]]
// Flood fill: visit every land cell connected to this one.
while (stack.length > 0) {
const [cr, cc] = stack.pop()
for (const [nr, nc] of [
[cr + 1, cc],
[cr - 1, cc],
[cr, cc + 1],
[cr, cc - 1],
]) {
// Inside the grid and still land: sink it now, so it's never pushed twice.
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] === '1') {
grid[nr][nc] = '0'
stack.push([nr, nc])
}
}
}
}
}
return count
}export default function numIslands(grid: string[][]): number {
const rows = grid.length
const cols = grid[0].length
let count = 0
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (grid[r][c] !== '1') continue // water, or land we already sank
// Unvisited land: a new island. Count it, then sink all of it.
count++
grid[r][c] = '0'
const stack: Array<[number, number]> = [[r, c]]
// Flood fill: visit every land cell connected to this one.
while (stack.length > 0) {
const [cr, cc] = stack.pop()!
for (const [nr, nc] of [
[cr + 1, cc],
[cr - 1, cc],
[cr, cc + 1],
[cr, cc - 1],
]) {
// Inside the grid and still land: sink it now, so it's never pushed twice.
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] === '1') {
grid[nr][nc] = '0'
stack.push([nr, nc])
}
}
}
}
}
return count
}def num_islands(grid: list[list[str]]) -> int:
rows, cols = len(grid), len(grid[0])
count = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] != "1":
continue # water, or land we already sank
# Unvisited land: a new island. Count it, then sink all of it.
count += 1
grid[r][c] = "0"
stack = [(r, c)]
# Flood fill: visit every land cell connected to this one.
while stack:
cr, cc = stack.pop()
for nr, nc in ((cr + 1, cc), (cr - 1, cc), (cr, cc + 1), (cr, cc - 1)):
# Inside the grid and still land: sink it now, so it's never pushed twice.
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == "1":
grid[nr][nc] = "0"
stack.append((nr, nc))
return count