昨天网不好,今天补上
题目描述
Given a 2d grid map of '1’s (land) and '0’s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
example1:
Input:
11110
11010
11000
00000
Output: 1
example2:
Input:
11000
11000
00100
00011
Output: 3
解题思路
这题以前做过,典型的dfs题目,具体步骤如下:
遍历grid数组,对于每一个字符为1的位置,
(1)岛屿数量++
(2)将与它相连的所有陆地,即字符1都遍历一遍并设为0,因为它们是属于同一个岛屿的;遍历采用深度遍历方式,每遇到一个1,就将它上下左右都遍历一遍
代码如下:
class Solution {
public int numIslands(char[][] grid) {
// dfs
if (grid == null || grid.length == 0 || grid[0].length == 0)
return 0;
int res = 0;
int row = grid.length, column = grid[0].length;
for (int i = 0; i < row; ++i) {
for (int j = 0; j < column; ++j) {
if (grid[i][j] == '1') {
res++;
dfs(grid, i, j);
}
}
}
return res;
}
public void dfs(char[][] grid, int row, int column) {
if (column < 0 || column >= grid[0].length)
return;
if (row < 0 || row >= grid.length)
return;
if (grid[row][column] == '0')
return;
grid[row][column] = '0';
dfs(grid, row - 1, column);
dfs(grid, row + 1, column);
dfs(grid, row, column - 1);
dfs(grid, row, column + 1);
}
}
该博客介绍了LeetCode 30天挑战的第17天问题——数独岛计数。博主通过给出的示例解释了如何在二维网格中计算陆地区域的数量。解题策略是使用深度优先搜索(DFS),当遇到陆地时,将其计数加一,并将相邻的陆地标记为水以避免重复计数。
739

被折叠的 条评论
为什么被折叠?



