来自labuladong:https://labuladong.github.io/algo/di-san-zha-24031/bao-li-sou-96f79/yi-wen-mia-4f482/
核心思想:dfs + 将遍历过的岛屿都淹没(原地操作节省空间)
举例:695.岛屿的最大面积 https://leetcode.cn/problems/max-area-of-island/
class Solution {
public:
vector<vector<int>> directed = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int maxAreaOfIsland(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size();
int res = 0;
for (int i = 0;i < n;i++)
{
for (int j = 0;j < m;j++)
{
res = max(res, dfs(grid, i, j, n, m));
}
}
return res;
}
int dfs(vector<vector<int>>& grid, int i, int j, int n, int m)
{
if (i < 0 || i >= n || j < 0 || j >= m || grid[i][j] == 0) // 超出边界或不是陆地直接返回
{
return 0;
}
int sum = 1;
grid[i][j] = 0; // 淹没这个块(岛屿的一部分)
for (auto & d : directed) // 此处如果要用 for (int i = 0...)遍历, 注意重新定义一个i 否则与输入的i冲突XD
{
sum += dfs(grid, i + d[0], j + d[1], n, m);
}
return sum;
}
};