给定一个由0和1组成的非空二维数组grid,一个岛由一组四联通(上下左右四方向)的1(表示陆地)组成。假定grid的四周都是水。
返回最大的岛。(没有岛则返回0)
样例 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]]
输出:6。
解释:注意不是11!因为是4方向联通。
样例 2:
输入:[[0,0,0,0,0,0,0,0]]
输出:0
思路:当找到一个点为1时,将其置0,搜寻上下左右四个点,看是否有其他点为1,如果有,递归继续寻找,记录搜寻到1的个数,记录最大数值。
class Solution {
public:
/**
* @param grid: a 2D array
* @return: the maximum area of an island in the given 2D array
*/
int maxAreaOfIsland(vector<vector<int>> &grid) {
// Write your code here
int row=grid.size();
int col=grid[0].size();
for (int i = 0; i < row; i++) {
/* code */
for (int j = 0; j < col; j++) {
/* code */
sum=0;
if(grid[i][j]) {Max=max(Max,count(grid,i,j));}
else continue;
}
}
return Max;
}
int count(vector<vector<int>> &grid,int i,int j)
{
int row=grid.size();
int col=grid[0].size();
if(i>=0&&i<row&&j>=0&&j<col)
{
if(grid[i][j])
{
grid[i][j]=0;
sum++;
count(grid,i-1,j);
count(grid,i+1,j);
count(grid,i,j-1);
count(grid,i,j+1);
}
}
return sum;
}
int Max=0;
int sum=0;
};