Created
December 29, 2024 06:37
-
-
Save marttp/204dad4e69bac160da02101e988dd20a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
private static final int[][] DIRS = new int[][] { | |
new int[] {-1,0}, | |
new int[] {1,0}, | |
new int[] {0,-1}, | |
new int[] {0,1} | |
}; | |
public int maxAreaOfIsland(int[][] grid) { | |
int ans = 0; | |
for (int r = 0; r < grid.length; r++) { | |
for (int c = 0; c < grid[r].length; c++) { | |
if (grid[r][c] == 1) { | |
int area = sumArea(grid, r, c); | |
if (area > ans) { | |
ans = area; | |
} | |
} | |
} | |
} | |
return ans; | |
} | |
private int sumArea(int[][] grid, int r, int c) { | |
if (!isInbound(grid, r, c) || grid[r][c] == 0) { | |
return 0; | |
} | |
int area = 1; | |
grid[r][c] = 0; | |
for (var dir : DIRS) { | |
area += sumArea(grid, r + dir[0], c + dir[1]); | |
} | |
return area; | |
} | |
private boolean isInbound(int[][] grid, int r, int c) { | |
return r >= 0 && r < grid.length && c >= 0 && c < grid[r].length; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment