class Solution { //总结 二维数组需要考虑n 在考虑m //需要看看左右上下 而不是仅考虑右下 public int numIslands(char[][] grid) { int n = grid.length; if(n==0)return 0; int m = grid[0].length; if(m==0)return 0; boolean flag [][] = new boolean [n][m]; int ans = 0 ; for(int i = 0 ; i < n ; i++ ) { for(int j = 0; j < m ;j++) { if(grid[i][j]=='1'&&flag[i][j]!=true) { bool_flag(flag,grid,i,j,n,m); ans++; } } } return ans; } public void bool_flag(boolean flag[][],char[][] grid,int i , int j,int n , int m) { if(i<0||j<0||i>=n||j>=m||grid[i][j]=='0'||flag[i][j]==true) { return ; } else { flag[i][j] = true; bool_flag(flag,grid,i+1,j,n,m); bool_flag(flag,grid,i-1,j,n,m); bool_flag(flag,grid,i,j+1,n,m); bool_flag(flag,grid,i,j-1,n,m); } } }