leetcode200 Number of Islands-zh
# 200. 岛屿数量 (opens new window)
English Version (opens new window)
# 题目描述
给你一个由 '1'
(陆地)和 '0'
(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
示例 1:
输入:grid = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ] 输出:1
示例 2:
输入:grid = [ ["1","1","0","0","0"], ["1","1","0","0","0"], ["0","0","1","0","0"], ["0","0","0","1","1"] ] 输出:3
提示:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j]
的值为'0'
或'1'
# 解法
BFS/DFS 均可
# Python3
1
# Java
1
# TypeScript
function numIslands(grid: string[][]): number {
let m = grid.length, n = grid[0].length;
let ans = 0;
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
if (grid[i][j] == '1') {
dfs(grid, i, j);
++ans;
}
}
}
return ans;
};
function dfs(grid: string[][], i: number, j: number) {
let m = grid.length, n = grid[0].length;
if (i < 0 || i > m - 1 || j < 0 || j > n - 1 || grid[i][j] == '0') {
return;
}
grid[i][j] = '0';
for (let [dx, dy] of [[0, 1], [0, -1], [1, 0], [-1, 0]]) {
let x = i + dx, y = j + dy;
dfs(grid, x, y);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# ...
1
编辑 (opens new window)
上次更新: 2021/10/30, 12:58:38