力扣题目
解题思路
java代码
力扣题目:
给你一个由 '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'
解题思路:
numIslands
方法负责计算岛屿的数量。它遍历整个网格,每当遇到一个 ‘1’ 时,就调用 dfs
方法去遍历这个岛屿的所有 ‘1’ 并将它们标记为 ‘0’,表示这个岛屿已经被计算过了。每次调用 dfs
方法时,如果当前元素是 ‘1’,则将其置为 ‘0’,并递归地对它的四个方向进行深度优先搜索。
以下是代码的详细解释:
numIslands
方法初始化岛屿数量count
为 0。- 使用双层循环遍历整个网格。
- 当遇到一个 ‘1’ 时,调用
dfs
方法,并将count
加一。 dfs
方法首先检查当前坐标是否越界或者当前元素是否为 ‘0’,如果是,则返回。- 如果当前元素是 ‘1’,则将其置为 ‘0’,然后对它的上下左右四个方向递归调用
dfs
方法。
java代码:
package org.example;
public class Leetcode200 {
public static void main(String[] args) {
char[][] grid = {{'1','1','1','1','0'},{'1','1','0','1','0'},{'1','1','0','0','0'},{'0','0','0','0','0'}};
System.out.println(new Leetcode200().numIslands(grid));
}
public int numIslands(char[][] grid) {
int count = 0;
for (int i = 0;i<grid.length;i++){
for(int j = 0;j<grid[0].length;j++){
if (grid[i][j] == '1'){
dfs(grid,i,j);
count++;
}
}
}
return count;
}
/**
* 深度优先遍历
* @param grid
* @param i
* @param j
*/
public static void dfs(char[][] grid,int i,int j){
if (i<0 || j<0 || i>=grid.length || j>=grid[0].length || grid[i][j] == '0'){
return;
}
// 遍历过就置为0
grid[i][j] = '0';
// 遍历上下左右
dfs(grid,i+1,j);
dfs(grid,i-1,j);
dfs(grid,i,j+1);
dfs(grid,i,j-1);
}
}
更多详细内容同步到公众号,感谢大家的支持!
并且没有任何收费项