classSolution{privateintROWS;privateintCOLS;publicintmaxAreaOfIsland(int[][] grid){ROWS= grid.length;COLS= grid[0].length;int res =0;// Check every cellfor(int row =0; row <ROWS;++row){for(int col =0; col <COLS;++col){// Record the maximum
res =Math.max(res,dfs(grid, row, col));}}return res;}privateintdfs(int[][] grid,int row,int col){// Check visited, inBound, and water// 這個return可以防止越過水到另一片陸地if(!isInBound(row, col)|| grid[row][col]==0){return0;}// Change to water indicates visited
grid[row][col]=0;// Sum up all the area including the current cellreturn1+dfs(grid, row +1, col)+dfs(grid, row -1, col)+dfs(grid, row, col +1)+dfs(grid, row, col -1);}privatebooleanisInBound(int row,int col){return row >=0&& row <ROWS&& col >=0&& col <COLS;}}