-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxIsland.java
More file actions
30 lines (28 loc) · 1.1 KB
/
MaxIsland.java
File metadata and controls
30 lines (28 loc) · 1.1 KB
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
// https://leetcode.com/problems/max-area-of-island/description/
public class MaxIsland {
public int maxAreaOfIsland(int[][] grid) {
int area = 0;
for (int i = 0; i < grid.length; i++)
for (int j = 0; j < grid[0].length; j++)
if (grid[i][j] == 1)
area = Math.max(area, getAreaOfIslandAt(i,j, grid));
return area;
}
private int getAreaOfIslandAt(int i, int j, int[][] grid) {
// if we go off the grid, this should not add to the island
if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length)
return 0;
else {
if (grid[i][j] == 0)
return 0;
else { // grid is a 1
grid[i][j] = 0; // mark as visited
// add the 1 to a search of surrounding grid points
return 1 + getAreaOfIslandAt(i+1, j, grid)
+ getAreaOfIslandAt(i-1, j, grid)
+ getAreaOfIslandAt(i, j+1, grid)
+ getAreaOfIslandAt(i, j-1, grid);
}
}
}
}