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.
给你一个二维数组,1代表岛屿,求岛屿的最大面积,只能四个方向搜索。
之间在杭电上做过一道类似的题解是求石油的面积的,这个比那个略难一点,要求出最大面积,深搜的应用
class Solution {
public:
int dfs(vector<vector<int>>& grid, int x0, int y0){
int n, m, sum=1;
n = grid.size();
m = grid[0].size();
grid[x0][y0] = 0; //当前元素设置为0,避免再次搜索到
int dir[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
for(int i=0; i<4; i++){
int x = x0 + dir[i][0];
int y = y0 + dir[i][1];
if(x>=0&&x=0&&y1)
sum+=dfs(grid, x, y);
}
return sum;
}
int maxAreaOfIsland(vector<vector<int>>& grid)
{
int mx = 0, n, m;
n = grid.size();
m = grid[0].size();
for(int i=0; ifor(int j=0; jif(grid[i][j] == 1)
mx = max(dfs(grid,i,j), mx);
}
return mx;
}
};
class Solution(object):
def dfs(self, grid, x0, y0):
s = 1
n = len(grid)
m = len(grid[0])
grid[x0][y0] = 0
dire = [[0,1],[0,-1],[1,0],[-1,0]]
for i in range(0,4):
x = x0 + dire[i][0]
y = y0 + dire[i][1]
if x>=0 and xand y>=0 and yand grid[x][y] == 1:
s = s + self.dfs(grid, x, y)
return s
def maxAreaOfIsland(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
mx = 0
n = len(grid)
m = len(grid[0])
for i in range(0, n):
for j in range(0, m):
if grid[i][j] == 1:
mx = max(mx, self.dfs(grid, i,j))
return mx