代码随想录|图论|08孤岛的总面积
leetcode:101. 孤岛的总面积
题目
题目描述
给定一个由 1(陆地)和 0(水)组成的矩阵,岛屿指的是由水平或垂直方向上相邻的陆地单元格组成的区域,且完全被水域单元格包围。孤岛是那些位于矩阵内部、所有单元格都不接触边缘的岛屿。
现在你需要计算所有孤岛的总面积,岛屿面积的计算方式为组成岛屿的陆地的总数。
输入描述
第一行包含两个整数 N, M,表示矩阵的行数和列数。之后 N 行,每行包含 M 个数字,数字为 1 或者 0。
输出描述
输出一个整数,表示所有孤岛的总面积,如果不存在孤岛,则输出 0。
输入示例
4 5
1 1 0 0 0
1 1 0 0 0
0 0 1 0 0
0 0 0 1 1
输出示例:
1
思路
从边缘上找到陆地,然后利用dfs或者bfs把周围的陆地进行标记(直接设为0),那么最后剩下的1就是孤岛。
这里不需要visited数据来标记,因为这里只需要把它们相邻的岛屿置0就行。
DFS版本
#include <bits/stdc++.h>
using namespace std;int dir[4][2] = {1, 0, 0, -1, -1, 0, 0, 1};
// dfs负责将相邻节点全部标记成0
void dfs(vector<vector<int>> &grid, int x, int y)
{// 终止条件if (grid[x][y] == 0){return;}// 处理当前节点grid[x][y] = 0;// 延伸周围节点for (int i = 0; i < 4; i++){int nextx = x + dir[i][0];int nexty = y + dir[i][1];if (nextx < 0 || nextx >= grid.size() || nexty < 0 || nexty >= grid[0].size())continue;dfs(grid, nextx, nexty);}
}int main()
{int n, m;cin >> n >> m;vector<vector<int>> grid(n, vector<int>(m, 0));for (int i = 0; i < n; i++){for (int j = 0; j < m; j++){cin >> grid[i][j];}}// 遍历第一行和最后一行for (int j = 0; j < m; j++){if (grid[0][j] == 1)dfs(grid, 0, j);if (grid[n - 1][j] == 1)dfs(grid, n - 1, j);}// 遍历第一列和最后一列for (int i = 0; i < n; i++){if (grid[i][0] == 1)dfs(grid, i, 0);if (grid[i][m - 1] == 1)dfs(grid, i, m - 1);}// 统计当前整个网格还有多少个1int result = 0;for (int i = 0; i < n; i++){for (int j = 0; j < m; j++){if (grid[i][j] == 1)result++;}}cout << result << endl;
}
BFS版本
// ======================================BFS======================================
#include <bits/stdc++.h>
using namespace std;
int dir[4][2] = {1, 0, 0, -1, -1, 0, 0, 1};
// bfs负责将相邻节点全部标记成0
void bfs(vector<vector<int>> &grid, int x, int y)
{queue<pair<int, int>> q;q.push({x, y});grid[x][y] = 0;while (!q.empty()){pair<int, int> cur = q.front();q.pop();int curx = cur.first;int cury = cur.second;for (int i = 0; i < 4; i++){int nextx = curx + dir[i][0];int nexty = cury + dir[i][1];if (nextx < 0 || nextx >= grid.size() || nexty < 0 || nexty >= grid[0].size())continue;if (grid[nextx][nexty] == 1){q.push({nextx, nexty});grid[nextx][nexty] = 0;}}}
}int main()
{int n, m;cin >> n >> m;vector<vector<int>> grid(n, vector<int>(m, 0));for (int i = 0; i < n; i++){for (int j = 0; j < m; j++){cin >> grid[i][j];}}// 遍历第一行和最后一行for (int j = 0; j < m; j++){if (grid[0][j] == 1)bfs(grid, 0, j);if (grid[n - 1][j] == 1)bfs(grid, n - 1, j);}// 遍历第一列和最后一列for (int i = 0; i < n; i++){if (grid[i][0] == 1)bfs(grid, i, 0);if (grid[i][m - 1] == 1)bfs(grid, i, m - 1);}// 统计当前整个网格还有多少个1int result = 0;for (int i = 0; i < n; i++){for (int j = 0; j < m; j++){if (grid[i][j] == 1)result++;}}cout << result << endl;return 0;
}
总结
逆向思考吗,有点意思
参考资料
代码随想录