Skip to content

Commit ef59326

Browse files
Update 0695-max-area-of-island.java
Removed unnecessary variables and make it a lot more like the Python solution in the video.
1 parent 0cc7ed4 commit ef59326

File tree

1 file changed

+25
-23
lines changed

1 file changed

+25
-23
lines changed

java/0695-max-area-of-island.java

+25-23
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,30 @@
11
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+
}
1410
}
1511

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;
2721
}
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+
}
2830
}

0 commit comments

Comments
 (0)