| 
1 | 1 | class Solution {  | 
2 |  | - | 
3 |  | -    public int maxAreaOfIsland(int[][] grid) {  | 
4 |  | -        int ans = 0;  | 
5 |  | -        int m = grid.length;  | 
6 |  | -        int n = grid[0].length;  | 
7 |  | -        for (int i = 0; i < m; i++) {  | 
8 |  | -            for (int j = 0; j < n; j++) {  | 
9 |  | -                if (grid[i][j] == 1) ans =  | 
10 |  | -                    Math.max(dfs(grid, i, j, m, n, new int[] { 0 }), ans);  | 
11 |  | -            }  | 
12 |  | -        }  | 
13 |  | -        return ans;  | 
 | 2 | +  int maxArea = 0;  | 
 | 3 | +    | 
 | 4 | +  public int maxAreaOfIsland(int[][] grid) {  | 
 | 5 | +    for (int i = 0; i < grid.length; i++) {  | 
 | 6 | +      for (int j = 0; j < grid[0].length; j++) {  | 
 | 7 | +        maxArea = Math.max(maxArea,   | 
 | 8 | +                    maxAreaOfIsland(grid, i, j));  | 
 | 9 | +      }  | 
14 | 10 |     }  | 
15 | 11 | 
 
  | 
16 |  | -    public int dfs(int[][] grid, int i, int j, int m, int n, int[] count) {  | 
17 |  | -        if (  | 
18 |  | -            i < 0 || j < 0 || i >= m || j >= n || grid[i][j] == 0  | 
19 |  | -        ) return count[0];  | 
20 |  | -        count[0]++;  | 
21 |  | -        grid[i][j] = 0;  | 
22 |  | -        dfs(grid, i - 1, j, m, n, count);  | 
23 |  | -        dfs(grid, i + 1, j, m, n, count);  | 
24 |  | -        dfs(grid, i, j - 1, m, n, count);  | 
25 |  | -        dfs(grid, i, j + 1, m, n, count);  | 
26 |  | -        return count[0];  | 
 | 12 | +    return maxArea;  | 
 | 13 | +  }  | 
 | 14 | + | 
 | 15 | +  public int maxAreaOfIsland(int[][] grid, int r, int c) {  | 
 | 16 | +    if (r < 0 || c < 0 ||   | 
 | 17 | +        r == grid.length ||   | 
 | 18 | +        c == grid[0].length ||   | 
 | 19 | +        grid[r][c] == 0) {  | 
 | 20 | +          return 0;    | 
27 | 21 |     }  | 
 | 22 | + | 
 | 23 | +    grid[r][c] = 0;  | 
 | 24 | +      | 
 | 25 | +    return (1 + maxAreaOfIsland(grid, r + 1, c) +  | 
 | 26 | +                maxAreaOfIsland(grid, r - 1, c) +  | 
 | 27 | +                maxAreaOfIsland(grid, r, c + 1) +  | 
 | 28 | +                maxAreaOfIsland(grid, r, c - 1));  | 
 | 29 | +  }  | 
28 | 30 | }  | 
0 commit comments