LeetCode200岛屿数量-----深度优先搜索
题目表述
给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
示例:
输入:
grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
输出:1
深度优先搜索
该题思路简单,就是找到有几块区域的1是水平方向或者竖直方向相邻,可以利用dfs,在四个方向上搜索,根节点从值为1的区域开始,访问过的区域1用visited数组记录下来,避免重复计算。每一次dfs搜索结束,就代表找到了一块陆地,接着再找根节点为1的且visited为false的区域。直到最终所有的陆地被访问完成。
class Solution {
private int count;
public int[][] directions = {{0,1},{0,-1},{1,0},{-1,0}};
public int numIslands(char[][] grid) {
boolean[][] visited = new boolean[grid.length][grid[0].length];
for(int i = 0; i < grid.length;i++){
for(int j = 0; j < grid[0].length;j++){
if(grid[i][j] == '1' && !visited[i][j]){
dfs(grid, visited,i,j);
count++;
}
}
}
return count;
}
public void dfs(char[][] grid, boolean[][] visited, int i, int j){
if(i <0 || i >= grid.length || j < 0 || j >= grid[0].length){
return;
}
if(visited[i][j] == true || grid[i][j] == '0'){
return ;
}
visited[i][j] = true;
for(int[] dir : directions){
dfs(grid, visited,i+dir[0],j+dir[1]);
}
}
}