题目
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代表岛屿,求岛屿的最大面积,只能四个方向搜索。
题解
之间在杭电上做过一道类似的题解是求石油的面积的,这个比那个略难一点,要求出最大面积,深搜的应用
C++代码
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<n&&y>=0&&y<m&&grid[x][y]==1)
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; i<n; i++)
for(int j=0; j<m; j++)
{
if(grid[i][j] == 1)
mx = max(dfs(grid,i,j), mx);
}
return mx;
}
};
python代码
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 x<n and y>=0 and y<m and 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