经典dfs将当前位置传入,标记和当前点一类的点,同时进行计数
class Solution {
public int[] pondSizes(int[][] land) {
List<Integer> res = new LinkedList<>();
int m = land.length,n = land[0].length;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(land[i][j] == 0) res.add(findArea(land,i,j));
}
}
int[] ans = res.stream().mapToInt(Integer::valueOf).toArray();
Arrays.sort(ans);
return ans;
}
public int findArea(int[][] land,int i,int j){
if(i < 0 || i >= land.length || j < 0 || j >= land[0].length || land[i][j] != 0){
return 0;
}
//走过池塘的进行标记
land[i][j] = -1;
//包含当前的池塘
int res = 1;
res += findArea(land,i+1,j+1);
res += findArea(land,i-1,j-1);
res += findArea(land,i+1,j);
res += findArea(land,i-1,j);
res += findArea(land,i,j+1);
res += findArea(land,i,j-1);
res += findArea(land,i+1,j-1);
res += findArea(land,i-1,j+1);
return res;
}
}