依然DFS,加上最大值判断,跟200. 岛屿数量基本一模一样
class Solution {
int res = Integer.MIN_VALUE;
int[][] dir = new int[][] { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } };
int r;
int c;
int count;
public int maxAreaOfIsland(int[][] grid) {
if(grid.length == 0)
return 0;
r = grid.length;
c = grid[0].length;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (grid[i][j] == 1) {
count = 0;
dfs(i, j, grid);
res = Math.max(res, count);
}
}
}
return res < 0 ? 0 : res;
}
public int dfs(int i, int j, int[][] grid) {
grid[i][j] = 0;
count++ ;
for (int[] d : dir) {
int newx = i + d[0];
int newy = j + d[1];
if (newx >= 0 && newx < r && newy >= 0 && newy < c) {
if(grid[newx][newy] == 1)
dfs(newx, newy, grid);
}
}
return count;
}
}