Description:
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.
题意:给定一个二维数组(只包含0或1),其中1表示岛屿,0表示海水,要求找出二维数组中岛屿的最大面积(要求岛屿是相连的,相连的方向只包含上下左右);
解法:这道题我们可以利用深度优先遍历的思想,如果当前位置是1(岛屿),那么我们寻找当前位置上下左右是岛屿的位置,在下个位置重复当前的操作,直到岛屿四周都是0(海水)为止;我们利用递归来实现这个算法,需要借助一个额外的二维数组来标记访问过的位置;
class Solution {
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[i].length; j++) {
if (!visited[i][j] && grid[i][j] == 1) {
visited[i][j] = true;
int localMax = localMaxAreaOfIsland(grid, visited, i, j) + 1;
max = localMax > max ? localMax : max;
}
}
}
return max;
}
private int localMaxAreaOfIsland(int[][] grid, boolean[][] visited, int r, int c){
int localMax = 0;
if (r-1 >= 0 && !visited[r-1][c] && grid[r-1][c] == 1) {
visited[r-1][c] = true;
localMax = localMax + localMaxAreaOfIsland(grid, visited, r-1, c) + 1;
} //move up
if (c+1 < grid[r].length && !visited[r][c+1] && grid[r][c+1] == 1) {
visited[r][c+1] = true;
localMax = localMax + localMaxAreaOfIsland(grid, visited, r, c+1) + 1;
} //move right
if (r+1 < grid.length && !visited[r+1][c] && grid[r+1][c] == 1) {
visited[r+1][c] = true;
localMax = localMax + localMaxAreaOfIsland(grid, visited, r+1, c) + 1;
} //move down
if (c-1 >= 0 && !visited[r][c-1] && grid[r][c-1] == 1) {
visited[r][c-1] = true;
localMax = localMax + localMaxAreaOfIsland(grid, visited, r, c-1) + 1;
} //move left
return localMax;
}
}