给定一个包含了一些 0 和 1的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合。你可以假设二维矩阵的四个边缘都被水包围着。
找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为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,因为岛屿只能包含水平或垂直的四个方向的‘1’。
示例 2:
[[0,0,0,0,0,0,0,0]]
对于上面这个给定的矩阵, 返回 0。
注意: 给定的矩阵grid 的长度和宽度都不超过 50。
BFS:
class Solution {
public:
vector<vector<int> > visit;
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};
int r;
int c;
int maxAreaOfIsland(vector<vector<int> >& grid) {
r = grid.size();
if(r == 0)
return 0;
c = grid[0].size();
visit = vector<vector<int> >(r, vector<int>(c, 0));
int res = 0;
for(int i = 0; i < r; i++)
{
for(int j = 0; j < c; j++)
{
if(visit[i][j] != 1 && grid[i][j] == 1)
{
visit[i][j] = 1;
res = max(res, BFS(grid, i, j));
}
}
}
return res;
}
int BFS(vector<vector<int> >& grid, int x, int y)
{
queue<pair<int, int> > q;
q.push(make_pair(x, y));
int cnt = 0;
while(!q.empty())
{
int xx = q.front().first;
int yy = q.front().second;
cnt++;
q.pop();
for(int i = 0; i < 4; i++)
{
int newx = xx + dx[i];
int newy = yy + dy[i];
if(newx < 0 || newx >= r || newy < 0 || newy >= c)
continue;
if(visit[newx][newy] == 1)
continue;
if(grid[newx][newy] == 0)
continue;
visit[newx][newy] = 1;
q.push(make_pair(newx, newy));
}
}
return cnt;
}
};
DFS:
class Solution {
public:
vector<vector<int> > visit;
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};
int r;
int c;
int maxAreaOfIsland(vector<vector<int> >& grid) {
r = grid.size();
if(r == 0)
return 0;
c = grid[0].size();
visit = vector<vector<int> >(r, vector<int>(c, 0));
int res = 0;
for(int i = 0; i < r; i++)
{
for(int j = 0; j < c; j++)
{
if(visit[i][j] != 1 && grid[i][j] == 1)
{
res = max(res, DFS(grid, i, j));
}
}
}
return res;
}
int DFS(vector<vector<int> >& grid, int x, int y)
{
int cnt = 1;
visit[x][y] = 1;
for(int i = 0; i < 4; i++)
{
int newx = x + dx[i];
int newy = y + dy[i];
if(newx < 0 || newx >= r || newy < 0 || newy >= c)
continue;
if(visit[newx][newy] == 1)
continue;
if(grid[newx][newy] == 0)
continue;
cnt += DFS(grid, newx, newy);
}
return cnt;
}
};