Number of Islands
Medium matrix · graphs
Description
Constraints
1 <= rows, cols <= 300
Examples
Input: grid = [[1,1,0],[0,1,0],[0,0,1]]
Output: 2
Hints (1)
- Flood fill each unvisited land cell.
Solutions
DFS flood fill. · Time O(rows*cols) · Space O(rows*cols)
func numIslands(grid [][]int) int {
rows, cols := len(grid), len(grid[0])
g := make([][]int, rows)
for i := range grid {
g[i] = append([]int{}, grid[i]...)
}
var sink func(r, c int)
sink = func(r, c int) {
if r < 0 || c < 0 || r >= rows || c >= cols || g[r][c] != 1 {
return
}
g[r][c] = 0
sink(r+1, c); sink(r-1, c); sink(r, c+1); sink(r, c-1)
}
count := 0
for r := 0; r < rows; r++ {
for c := 0; c < cols; c++ {
if g[r][c] == 1 {
count++
sink(r, c)
}
}
}
return count
}
DFS flood fill. · Time O(rows*cols) · Space O(rows*cols)
function numIslands(grid) {
const rows = grid.length, cols = grid[0].length;
const g = grid.map(r => [...r]);
let count = 0;
const sink = (r, c) => {
if (r < 0 || c < 0 || r >= rows || c >= cols || g[r][c] !== 1) return;
g[r][c] = 0;
sink(r + 1, c); sink(r - 1, c); sink(r, c + 1); sink(r, c - 1);
};
for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) if (g[r][c] === 1) { count++; sink(r, c); }
return count;
}
DFS flood fill. · Time O(rows*cols) · Space O(rows*cols)
function numIslands($grid) {
$rows = count($grid); $cols = count($grid[0]); $count = 0;
$sink = function ($r, $c) use (&$sink, &$grid, $rows, $cols) {
if ($r < 0 || $c < 0 || $r >= $rows || $c >= $cols || $grid[$r][$c] !== 1) { return; }
$grid[$r][$c] = 0;
$sink($r + 1, $c); $sink($r - 1, $c); $sink($r, $c + 1); $sink($r, $c - 1);
};
for ($r = 0; $r < $rows; $r++) {
for ($c = 0; $c < $cols; $c++) {
if ($grid[$r][$c] === 1) { $count++; $sink($r, $c); }
}
}
return $count;
}
DFS flood fill. · Time O(rows*cols) · Space O(rows*cols)
def numIslands(grid):
rows, cols = len(grid), len(grid[0])
g = [row[:] for row in grid]
def sink(r, c):
if r < 0 or c < 0 or r >= rows or c >= cols or g[r][c] != 1:
return
g[r][c] = 0
sink(r+1,c); sink(r-1,c); sink(r,c+1); sink(r,c-1)
count = 0
for r in range(rows):
for c in range(cols):
if g[r][c] == 1:
count += 1
sink(r, c)
return count
DFS flood fill. · Time O(rows*cols) · Space O(rows*cols)
function numIslands(grid: number[][]): number {
const rows = grid.length, cols = grid[0].length;
const g = grid.map(r => [...r]);
let count = 0;
const sink = (r: number, c: number): void => {
if (r < 0 || c < 0 || r >= rows || c >= cols || g[r][c] !== 1) return;
g[r][c] = 0;
sink(r + 1, c); sink(r - 1, c); sink(r, c + 1); sink(r, c - 1);
};
for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) if (g[r][c] === 1) { count++; sink(r, c); }
return count;
}
Create a free account to submit solutions, track progress and save problems.
Create account