Skip to content

Commit 8f44016

Browse files
authored
Update Max Area of Island.java
1 parent f83ba4f commit 8f44016

File tree

1 file changed

+34
-16
lines changed

1 file changed

+34
-16
lines changed

Easy/Max Area of Island.java

Lines changed: 34 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,45 @@
11
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+
35
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;
68
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+
}
1116
}
1217
}
1318
return maxArea;
1419
}
1520

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+
}
2438
}
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;
2644
}
2745
}

0 commit comments

Comments
 (0)