<>1. subject
<>2. thinking
classical DFS+ Template of backtracking routine , This problem is more troublesome is the need to traverse 8 Three directions
Java Explanation of language problems
class Solution { List<Integer> array = new ArrayList<Integer>(); int rowLen;
int colLen; public int[] pondSizes(int[][] land) { rowLen = land.length; colLen
= land[0].length; for(int i = 0;i<rowLen;i++){ for(int j = 0;j<colLen;j++){ if(
land[i][j] == 0){ array.add(dfs(land,i,j)); land[i][j] = 0; } } } Collections.
sort(array); int size = array.size(); int[] result = new int[size]; for(int i =
0;i<size;i++){ result[i] = array.get(i).intValue(); } return result; } public
int dfs(int[][] land,int i,int j){ if(!checkBoard(land,i,j)){ return 0; } int
count= 1; land[i][j] = -1; count+=dfs(land,i-1,j-1); // top left corner count+=dfs(land,i-1,
j); // Right above count+=dfs(land,i-1,j+1); // Top right corner count+=dfs(land,i,j+1); // The one on the right count+=
dfs(land,i+1,j+1); // Lower right corner count+=dfs(land,i+1,j); // Right below count+=dfs(land,i+1,j-1);
// lower left quarter count+=dfs(land,i,j-1); // The one on the left return count; } public boolean checkBoard(
int[][] land,int i,int j){ if(i>=rowLen || i<0) return false; if(j>=colLen || j<
0) return false; return land[i][j] == 0; } }
<>3. summary
Don't forget to go back ,DFS Marks made in the process need to be restored , Otherwise, the stack will overflow
Technology