-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIslandMaxArea.java
68 lines (57 loc) · 1.71 KB
/
IslandMaxArea.java
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package org.sean.recursive;
/***
* 695. Max Area of Island
*/
public class IslandMaxArea {
private boolean[][] visited;
private int max = 0;
int[][] moves = new int[][] {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
/***
*
* 1. Mark all the visited cells
*
* 2. Traverse the cells with value 1 recursively, and calculate
* the total area along the way
*
*/
public int maxAreaOfIsland(int[][] grid) {
int row = grid.length;
int column = grid[0].length;
visited = new boolean[row][column];
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
int cellVal = grid[i][j];
if (cellVal == 1) {
calcArea(grid, i, j, 0);
} else {
visited[i][j] = true;
}
}
}
return max;
}
private int calcArea(int[][] grid, int r, int c, int currSum) {
if (visited[r][c]) return currSum;
currSum += 1;
int row = grid.length;
int col = grid[0].length;
int sum = currSum;
visited[r][c] = true;
for (int[] move : moves) {
int x = c + move[1];
int y = r + move[0];
if (x >= 0 && x < col && y >= 0 && y < row) {
int cellVal = grid[y][x];
if (cellVal == 1) {
// add up all extended cells from the 4 directions
int n = calcArea(grid, y, x, currSum);
sum += n - currSum;
} else {
visited[y][x] = true;
}
}
}
max = Math.max(max, sum);
return sum;
}
}