https://leetcode.com/problems/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.
class Solution {
int count = 0;
public int maxAreaOfIsland(int[][] grid) {
boolean[][] visited = new boolean[grid.length][grid[0].length];
int max = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 1 && !visited[i][j]) {
//dfs(i, j, grid, visited);
bfs(i, j, grid, visited);
max = Math.max(max, count);
count = 0;
}
}
}
return max;
}
public void dfs(int r, int c, int[][] grid, boolean[][] visited) {
if (r >= grid.length || r < 0 || c >= grid[0].length || c < 0 || grid[r][c] == 0 || visited[r][c])
return;
count++;
visited[r][c] = true;
int[] dx = {1, 0, 0, -1};
int[] dy = {0, 1, -1, 0};
for (int i = 0; i < 4; i++) {
dfs(r + dx[i], c + dy[i], grid, visited);
}
}
public void bfs(int r, int c, int[][] grid, boolean[][] visited) {
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[]{r, c});
visited[r][c] = true;
int[] dx = {1, 0, 0, -1};
int[] dy = {0, 1, -1, 0};
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
int[] curr = queue.remove();
count++;
for (int j = 0; j < 4; j++) {
r = curr[0] + dx[j];
c = curr[1] + dy[j];
if (r >= grid.length || r < 0 || c >= grid[0].length || c < 0 || grid[r][c] == 0 || visited[r][c])
continue;
visited[r][c] = true;
queue.add(new int[]{r, c});
}
}
}
}
}