cpp
#include<bits/stdc++.h>
using namespace std;
int dfs(vector<vector<int>>& mp, vector<vector<int>>& visit, int y, int x, int s, int& notEdge){
if (mp[y][x] == 0 || visit[y][x] == 1) return s * notEdge;
if (mp[y][x] == 1 && visit[y][x] == 0){
s++;
visit[y][x] = 1;
}
if (y == 0 || y == mp.size() - 1 || x == 0 || x == mp[0].size() - 1) notEdge = 0;
if (y > 0) s = dfs(mp, visit, y - 1, x, s, notEdge);
if (x > 0) s = dfs(mp, visit, y, x - 1, s, notEdge);
if (y < mp.size() - 1) s = dfs(mp, visit, y + 1, x, s, notEdge);
if (x < mp[0].size() - 1) s = dfs(mp, visit, y, x + 1, s, notEdge);
return s * notEdge;
}
int main(){
int n, m;
cin >> n >> m;
int result = 0;
vector<vector<int>> mp(n, vector<int>(m, 0));
vector<vector<int>> visit(n, vector<int>(m, 0));
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
cin >> mp[i][j];
}
}
int isEdge;
for (int i = 0; i < mp.size(); i++){
for (int j = 0; j < mp[0].size(); j++){
if (mp[i][j] == 1 && visit[i][j] == 0){
isEdge = 1;
result += dfs(mp, visit, i, j, 0, isEdge);
}
}
}
cout << result;
return 0;
}
dfs版本,在之前求总面积的基础上增加了判断是否有有边缘位置元素的部分,所以增加了一个notEdge变量,在遇到边缘元素时标记为0,以使所有输出均变为0,此外需要注意,即使遇到了边缘元素也需要先将所有陆地遍历并在visit上标记。毕竟做人需要有始有终)
cpp
#include<bits/stdc++.h>
using namespace std;
int bfs(vector<vector<int>>& mp, vector<vector<int>>& visit, int y, int x){
int result = 0;
int notEdge = 1;
queue<pair<int, int>> q;
q.push({y, x});
visit[y][x] = 1;
result++;
while(!q.empty()){
pair<int, int> tmp = q.front();
q.pop();
int tmpy = tmp.first, tmpx = tmp.second;
if (tmpy == 0 || tmpx == 0 || tmpy == mp.size() - 1 || tmpx == mp[0].size() - 1) notEdge = 0;
if (tmpy > 0){
if (mp[tmpy - 1][tmpx] == 1 && visit[tmpy - 1][tmpx] == 0){
q.push({tmpy - 1, tmpx});
visit[tmpy - 1][tmpx] = 1;
result++;
}
}
if (tmpx > 0){
if (mp[tmpy][tmpx - 1] == 1 && visit[tmpy][tmpx - 1] == 0){
q.push({tmpy, tmpx - 1});
visit[tmpy][tmpx - 1] = 1;
result++;
}
}
if (tmpy < mp.size() - 1){
if (mp[tmpy + 1][tmpx] == 1 && visit[tmpy + 1][tmpx] == 0){
q.push({tmpy + 1, tmpx});
visit[tmpy + 1][tmpx] = 1;
result++;
}
}
if (tmpx < mp[0].size() - 1){
if (mp[tmpy][tmpx + 1] == 1 && visit[tmpy][tmpx + 1] == 0){
q.push({tmpy, tmpx + 1});
visit[tmpy][tmpx + 1] = 1;
result++;
}
}
}
return result * notEdge;
}
int main(){
int n, m;
cin >> n >> m;
int result = 0;
vector<vector<int>> mp(n, vector<int>(m, 0));
vector<vector<int>> visit(n, vector<int>(m, 0));
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
cin >> mp[i][j];
}
}
for (int i = 0; i < mp.size(); i++){
for (int j = 0; j < mp[0].size(); j++){
if (mp[i][j] == 1 && visit[i][j] == 0){
result += bfs(mp, visit, i, j);
}
}
}
cout << result;
return 0;
}
bfs的版本,bfs不需要做递归回溯,所以函数的变量还是不变,只需要在内部增加一个标记是否有边缘元素的变量即可。