LeetCode Q 695 - Max Area of Island
Given a non-empty 2D array grid of 0’s and 1’s, an island is a group of 1’s (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)
Example 1:
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]
Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.
Example 2:
[[0,0,0,0,0,0,0,0]]
Given the above grid, return 0.
Note: The length of each dimension in the given grid does not exceed 50.
Solution
Solution 1 : DFS
Code:
private static final int[] DIRS = new int[]{1, 0, -1, 0, 1};
public int maxAreaOfIsland(int[][] grid) {
int R = grid.length, C = grid[0].length;
int max = 0;
for (int r = 0; r < R; r++) {
for (int c = 0; c < C; c++) {
if (grid[r][c] == 1) {
max = Math.max(max, dfs(grid, r, c));
}
}
}
return max;
}
private int dfs (int[][] grid, int r, int c) {
int res = 1;
grid[r][c] = 0;
for (int i = 0; i < 4; i++) {
int nr = r + DIRS[i];
int nc = c + DIRS[i + 1];
if (nr >= 0 && nc >= 0 && nr < grid.length && nc < grid[0].length && grid[nr][nc] == 1)
res += dfs(grid, nr, nc);
}
return res;
}
Solution 2 : BFS
Code:
private static final int[] DIRS = new int[]{1, 0, -1, 0, 1};
public int maxAreaOfIsland(int[][] grid) {
int R = grid.length, C = grid[0].length;
int max = 0;
for (int r = 0; r < R; r++) {
for (int c = 0; c < C; c++) {
if (grid[r][c] == 1) {
max = Math.max(max, bfs(grid, r, c));
}
}
}
return max;
}
private int bfs (int[][] grid, int r, int c) {
int res = 0;
int R = grid.length, C= grid[0].length;
Queue<int[]> que = new LinkedList<>();
que.offer(new int[]{r, c});
grid[r][c] = 0;
while (!que.isEmpty()) {
int[] curr = que.poll();
res++;
for (int i = 0; i < 4; i++) {
int nr = curr[0] + DIRS[i];
int nc = curr[1] + DISR[i + 1];
if (nr >= 0 && nc >= 0 && nr < R && nc < C
&& grid[nr][nc] == 1) {
que.offer(new int[]{nr, nc});
grid[nr][nc] = 0; // set node to be 0 as soon as we offer it into the queue.
}
}
}
return res;
}