给定一个包含了一些 0
和 1
的非空二维数组 grid
。
一个 岛屿 是由一些相邻的 1
(代表土地) 构成的组合,这里的「相邻」要求两个 1
必须在水平或者竖直方向上相邻。你可以假设 grid
的四个边缘都被 0
(代表水)包围着。
找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为 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。
class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
R = grid.size();
if(R == 0) return 0;
C = grid[0].size();
if(C == 0) return 0;
visited = vector<bool>(R*C, false);
this->grid = grid;
int res = 0;
for(int i = 0; i < R * C; i++){
int x = i / C, y = i % C;
if(grid[x][y] == 1 && !visited[i]){
res = max(res, dfs(i));
}
}
return res;
}
int dfs(int v){
visited[v] = true;
int res = 1;
int x = v / C, y = v % C;
// cout<<v<<endl;
for(int i = 0; i< 4; i++){
int nextX = x + dirs[i][0];
int nextY = y + dirs[i][1];
if(inArea(nextX, nextY) && grid[nextX][nextY] == 1 && !visited[nextX * C + nextY]){
res += dfs(nextX * C + nextY);
}
}
return res;
}
bool inArea(int x, int y){
return x >=0 && x < R && y >= 0 && y < C;
}
private:
vector<vector<int>> grid;
vector<bool> visited;
int R;
int C;
int dirs[4][2]={{-1,0},{0, 1},{1, 0}, {0, -1}};
};
优化
class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
R = grid.size();
if(R == 0) return 0;
C = grid[0].size();
if(C == 0) return 0;
visited = vector<bool>(R*C, false);
this->grid = grid;
int res = 0;
for(int x = 0; x < R; x++){
for(int y = 0; y < C; y++){
if(grid[x][y] == 1 ){
res = max(res, dfs(x, y));
}
}
}
return res;
}
int dfs(int x, int y){
if(x < 0 || x >= R || y < 0 || y >= C || grid[x][y] == 0) return 0;
grid[x][y] = 0;
int res = 1;
res += dfs(x - 1, y);
res += dfs(x, y + 1);
res += dfs(x + 1, y);
res += dfs(x, y - 1);
return res;
}
bool inArea(int x, int y){
return x >=0 && x < R && y >= 0 && y < C;
}
private:
vector<vector<int>> grid;
vector<bool> visited;
int R;
int C;
int dirs[4][2]={{-1,0},{0, 1},{1, 0}, {0, -1}};
};