解题思路:
岛屿题目一般使用dfs。
1.判断是否越界
2.用0,1,2三个状态标识当前格子的状态(三个状态比两个状态更清晰)
3.向周围四个方向遍历
class Solution {public int numIslands(char[][] grid) {int cnt = 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);cnt++;}}}return cnt;}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' || grid[i][j] == '2') 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);}
}