LeetCode200
岛屿数量
岛屿问题确实很经典,有Dfs(深度优先搜索)和Bfs(广度优先搜索)和并查集等多种解题方式,分别对应栈、队列以及树型的数据结构
相比较LeetCode三种官方题解,这道题感觉使用Dfs会更加容易理解一些
题目直接拷过来 内容及用例大致如下
给你一个由 ‘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'
public class Dfs{
// LeetCode深搜官方题解 乍一眼看上去感觉深搜真的很简单粗暴
public static void main(String[] args) {
int[][] grid = {
{
1,1,1,1,0},{
1,1,0,1,0},{
1,1,0,0,0},{
0,0,0,0,0}};
int row = grid.length;
int col = grid[0].length;
int numberOfIsland = 0;
for( int r = 0; r < row; ++r){
//依次去遍历,如果遇到陆地格子,直接将岛屿数量加一
for( int c = 0 ; c < col; c++){
if(grid[r][c] == 1){
++numberOfIsland;
dfs(grid,r,c);
}
}
}
System.out.println(numberOfIsland);
}
private static