100道面试必会算法-18-岛屿问题(数量、周长、面积)
题目描述
给你一个由 '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
解题思路
采用深度优先遍历思想,传送门:https://leetcode.cn/problems/number-of-islands/solutions/211211/dao-yu-lei-wen-ti-de-tong-yong-jie-fa-dfs-bian-li-/
值得注意一个问题
以上写法问题,if内判断是需要注意顺序的,倘若发生越界要注意判断条件,grid[i][j]!= '1'
的判断需要在i<0,j<0后,若先进行判断则可能会发生越界错误
代码
public class LC13 {
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;
}
private void dfs(char[][] grid, int i, int j) {
// 第一种写法(不通过)
// if (i >= grid.length || j >= grid[0].length || grid[i][j] != '1' || i<0|| j<0)return;
// 第二种写法(通过)
if (i<0 || j<0 || i >= grid.length || j >= grid[0].length || grid[i][j] != '1' )return;
// 第三种写法(通过)
// if (i >= grid.length || j >= grid[0].length || i < 0 || j < 0) {
// return;
// }
// if (grid[i][j] != '1') {
// return;
// }
grid[i][j]='2';
dfs(grid, i-1, j);
dfs(grid, i+1, j);
dfs(grid, i, j-1);
dfs(grid, i, j+1);
}
public static void main(String[] args) {
// 创建一个示例对象
LC13 main = new LC13();
// 测试用例
char[][] grid = {
{'1', '1', '0', '0', '0'},
{'1', '1', '0', '0', '0'},
{'0', '0', '1', '0', '0'},
{'0', '0', '0', '1', '1'}
};
// 调用numIslands方法计算岛屿数量
int islands = main.numIslands(grid);
// 输出结果
System.out.println("岛屿数量为:" + islands);
}
}
面积
int area(int[][] grid, int r, int c) {
return 1
+ area(grid, r - 1, c)
+ area(grid, r + 1, c)
+ area(grid, r, c - 1)
+ area(grid, r, c + 1);
}
周长
c)
+ area(grid, r + 1, c)
+ area(grid, r, c - 1)
+ area(grid, r, c + 1);
}
周长