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.
思路:BFS和DFS都可以做。面试的时候,我自己觉得用BFS比较好,因为matrix一旦很大的话,会爆栈,BFS写比较自然;
class Solution {
public int maxAreaOfIsland(int[][] grid) {
int maxcount = 0;
int m = grid.length;
int n = grid[0].length;
boolean[][] visited = new boolean[m][n];
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(grid[i][j] == 1 && !visited[i][j]) {
//maxcount = Math.max(maxcount, bfs(grid, i, j, visited));
maxcount = Math.max(maxcount, dfs(grid, i, j, visited));
}
}
}
return maxcount;
}
private int[][] dirs = new int[][]{{0,1},{0,-1},{-1,0},{1,0}};
private int dfs(int[][] grid, int x, int y, boolean[][] visited) {
if(x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || visited[x][y]) {
return 0;
}
int count = 0;
if(grid[x][y] == 1) {
count++;
visited[x][y] = true;
for(int[] dir: dirs) {
int nx = x + dir[0];
int ny = y + dir[1];
count += dfs(grid, nx, ny, visited);
}
}
return count;
}
private int bfs(int[][] grid, int x, int y, boolean[][] visited) {
int m = grid.length;
int n = grid[0].length;
int count = 0;
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{x, y});
visited[x][y] = true;
while(!queue.isEmpty()) {
int[] node = queue.poll();
count++;
for(int[] dir: dirs) {
int nx = node[0] + dir[0];
int ny = node[1] + dir[1];
if(0 <= nx && nx < m && 0 <= ny && ny < n
&& !visited[nx][ny] && grid[nx][ny] == 1) {
queue.offer(new int[]{nx, ny});
visited[nx][ny] = true;
}
}
}
return count;
}
}