问题链接
200. 岛屿数量
问题描述
给你一个由 1
(陆地)和 0
(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
示例
输入:grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
输出:1
输入:grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
输出:3
解题思路
采用沉岛策略,遍历网格,当发现岛屿(找到“1”)时,将这整一块岛屿沉入海底(利用深度优先搜索算法)。
代码示例(JAVA)
class Solution {
int[] arrX = {1, -1, 0, 0};
int[] arrY = {0, 0, -1, 1};
public int numIslands(char[][] grid) {
int count = 0;
int len = grid.length;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == '1') {
grid[i][j] = '0';
count++;
dfs(grid, i, j);
}
}
}
return count;
}
public void dfs(char[][] grid, int x, int y) {
for (int i = 0; i < arrX.length; i++) {
if (x + arrX[i] >= 0 && x + arrX[i] < grid.length && y + arrY[i] >= 0 && y + arrY[i] < grid[0].length
&& grid[x + arrX[i]][y + arrY[i]] == '1') {
grid[x + arrX[i]][y + arrY[i]] = '0';
dfs(grid, x + arrX[i], y + arrY[i]);
}
}
}
}
网友评论