题目描述:
给定一个包含了一些 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。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/max-area-of-island
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
直接BFS即可。
参考代码:
typedef struct Loc {
int x;
int y;
};
int BFS(Loc loc,vector<vector<int>>& grid) {
int ans = 1;
int dx[4] = { 0, 0, -1, 1 };
int dy[4] = { 1, -1, 0, 0 };
queue<Loc> que;
que.push(loc);
grid[loc.y][loc.x] = 0;
while (!que.empty()){
Loc tmp = que.front();
que.pop();
for (int i = 0; i < 4; i++) {
if ((tmp.y + dy[i]) >= 0 && (tmp.y + dy[i]) < grid.size() &&
(tmp.x + dx[i]) >= 0 && (tmp.x + dx[i]) < grid[0].size() &&
grid[tmp.y + dy[i]][tmp.x + dx[i]] == 1) {
Loc newLoc;
newLoc.x = tmp.x + dx[i];
newLoc.y = tmp.y + dy[i];
que.push(newLoc);
ans += 1;
grid[newLoc.y][newLoc.x] = 0;
}
}
}
return ans;
}
int maxAreaOfIsland(vector<vector<int>>& grid) {
int ans = 0;
for (int i = 0; i < grid.size(); i++) {
for (int j = 0; j < grid[i].size(); j++) {
if (grid[i][j] == 1) {
Loc loc;
loc.x = j;
loc.y = i;
int tmp = BFS(loc, grid);
if (tmp > ans)
ans = tmp;
}
}
}
return ans;
}