岛屿的最大面积
给定一个包含了一些 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。
来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/ma…
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路(超过99.80%)
第一眼看到,吓得我不敢动,因为DFS我不熟。
放了一天,简单题刷完之后,还是得面对。
其实没那么恐怖,递归回溯,遍历到一个节点就给它置空掉,并计数。
代码实现
int checkIsland(vector<vector<int>>& grid, int x, int y) {
int count = 0;
if (grid[x][y] == 0)
return count;
else {
grid[x][y] = 0;
count++;
//上
if (x - 1 >= 0)
count += checkIsland(grid, x - 1, y);
//右
if ((y + 1) < grid[0].size())
count += checkIsland(grid, x, y + 1);
//下
if ((x + 1) < grid.size())
count += checkIsland(grid, x + 1, y);
//左
if ((y - 1) >= 0)
count += checkIsland(grid, x, y - 1);
}
return count;
}
int maxAreaOfIsland(vector<vector<int>>& grid) {
if (grid.size() == 0)
return 0;
int max = 0;
for (int i = 0; i < grid.size(); i++) {
for (int j = 0; j < grid[0].size(); j++) {
int temp = checkIsland(grid, i, j);
if (temp > max) {
max = temp;
}
}
}
return max;
}