1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class Solution { private int[][] DIRECTIONS = new int[][] { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
public int maxAreaOfIsland(int[][] grid) { int ans = 0; for (int row = 0; row < grid.length; row++) { for (int col = 0; col < grid[0].length; col++) { if (grid[row][col] == 1) { ans = Math.max(ans, dfs(grid, row, col)); } } } return ans; }
private int dfs(int[][] grid, int row, int col) { grid[row][col] = 0; int ans = 1; for (int[] direction : DIRECTIONS) { int newRow = row + direction[0]; int newCol = col + direction[1]; if (!isOutOfBound(grid, newRow, newCol) && grid[newRow][newCol] != 0) { ans += dfs(grid, newRow, newCol); } } return ans; }
private boolean isOutOfBound(int[][] grid, int row, int col) { return row < 0 || row >= grid.length || col < 0 || col >= grid[0].length; } }
|