import java.util.*; public class Solution { //深度优先遍历为1的周围将周围置为0,这样直接遍历数组计算有1的值就是结果 public int solve (char[][] grid) { // write code here int l1 = grid.length; //空矩阵 if(l1==0){ return 0; } int l2 = grid[0].length; int ret = 0; for(int i=0;i<l1;i++){ for(int j=0;j<l2;j++){ if(grid[i][j]=='1'){ //遇到有1的将周围全部置为0,这样就不用考虑有相邻1重复计算的清空 ret++; dfs(grid,i,j); } } } return ret; } //遍历ij附近四个方向如果是1就置为0 public void dfs(char[][] grid ,int i,int j){ int l1 = grid.length; int l2 = grid[0].length; //置为0.递归的执行 grid[i][j]='0'; //遍历四个方向。如果是1就置为0 //前,注意向前遍历时i-1是>=0 if(i-1>=0 && grid[i-1][j]=='1'){ //继续递归,查看再前一个是否页为1 dfs(grid,i-1,j); } //后 if(i+1<l1 && grid[i+1][j]=='1'){ dfs(grid,i+1,j); } //左 if(j-1>=0 && grid[i][j-1]=='1'){ dfs(grid,i,j-1); } //右 if(j+1<l2 && grid[i][j+1]=='1'){ dfs(grid,i,j+1); } } }