|
1 | 1 | class Solution {
|
2 |
| - int[][] dirs = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; |
| 2 | + |
| 3 | + private static final int[][] DIRS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; |
| 4 | + |
3 | 5 | public int maxAreaOfIsland(int[][] grid) {
|
4 |
| - int m = grid.length; |
5 |
| - int n = grid[0].length; |
| 6 | + int rows = grid.length; |
| 7 | + int cols = grid[0].length; |
6 | 8 | int maxArea = 0;
|
7 |
| - boolean[][] visited = new boolean[m][n]; |
8 |
| - for (int i = 0; i < m; i++) { |
9 |
| - for (int j = 0; j < n; j++) { |
10 |
| - maxArea = Math.max(maxArea, helper(grid, i, j, m, n, visited)); |
| 9 | + for (int i = 0; i < rows; i++) { |
| 10 | + for (int j = 0; j < cols; j++) { |
| 11 | + if (grid[i][j] != 0) { |
| 12 | + grid[i][j] = 0; |
| 13 | + int currentArea = getArea(grid, i, j); |
| 14 | + maxArea = Math.max(maxArea, currentArea); |
| 15 | + } |
11 | 16 | }
|
12 | 17 | }
|
13 | 18 | return maxArea;
|
14 | 19 | }
|
15 | 20 |
|
16 |
| - private int helper(int[][] grid, int i, int j, int m, int n, boolean[][] visited) { |
17 |
| - if (i < 0 || i >= m || j < 0 || j >= n || visited[i][j] || grid[i][j] == 0) { |
18 |
| - return 0; |
19 |
| - } |
20 |
| - int curr = 1; |
21 |
| - visited[i][j] = true; |
22 |
| - for (int[] dir : dirs) { |
23 |
| - curr += helper(grid, i + dir[0], j + dir[1], m, n, visited); |
| 21 | + private int getArea(int[][] grid, int i, int j) { |
| 22 | + int currentArea = 0; |
| 23 | + Queue<int[]> queue = new LinkedList<>(); |
| 24 | + queue.add(new int[]{i, j}); |
| 25 | + while (!queue.isEmpty()) { |
| 26 | + int[] removed = queue.remove(); |
| 27 | + int currX = removed[0]; |
| 28 | + int currY = removed[1]; |
| 29 | + currentArea++; |
| 30 | + for (int[] dir : DIRS) { |
| 31 | + int newX = dir[0] + currX; |
| 32 | + int newY = dir[1] + currY; |
| 33 | + if (isValidCoordinate(grid, newX, newY) && grid[newX][newY] == 1) { |
| 34 | + queue.add(new int[]{newX, newY}); |
| 35 | + grid[newX][newY] = 0; |
| 36 | + } |
| 37 | + } |
24 | 38 | }
|
25 |
| - return curr; |
| 39 | + return currentArea; |
| 40 | + } |
| 41 | + |
| 42 | + private boolean isValidCoordinate(int[][] grid, int i, int j) { |
| 43 | + return i >= 0 && j >= 0 && i < grid.length && j < grid[0].length; |
26 | 44 | }
|
27 | 45 | }
|
0 commit comments