LeetCode 200. 岛屿数量
class Solution { 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; } public 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'; // 从 (i, j) 向此点的上下左右 (i+1,j),(i-1,j),(i,j+1),(i,j-1) 做深度搜索 dfs(grid,i + 1,j); dfs(grid,i - 1,j); dfs(grid,i,j + 1); dfs(grid,i,j - 1); } }