这个题很像水坑计数
http://poj.org/problem?id=2386
可以使用BFS从里往外搜
这是我的水坑计数答案(我懒得改)
#include <bits/stdc++.h>
using namespace std;
bool isValid(int x, int y, int n, int m, vector<vector<bool>>& visited) {
return (x >= 0 && y >= 0 && x < n && y < m && !visited[x][y]);
}
void BFS(vector<string>& land, int n, int m, int x, int y, vector<vector<bool>>& visited) {
int dx[] = {-1, -1, -1, 0, 0, 1, 1, 1};
int dy[] = {-1, 0, 1, -1, 1, -1, 0, 1};
queue<pair<int,int>> q;
visited[x][y] = true;
q.push({x, y});
while (!q.empty()) {
int currX = q.front().first;
int currY = q.front().second;
q.pop();
for (int i = 0; i < 8; i++) {
int newX = currX + dx[i];
int newY = currY + dy[i];
if (isValid(newX, newY, n, m, visited) && land[newX][newY] == '1') {
visited[newX][newY] = true;
q.push({newX, newY});
}
}
}
}
int countDistinctPools(vector<string>& land, int n, int m) {
vector<vector<bool>> visited(n, vector<bool>(m, false));
int distinctPools = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (!visited[i][j] && land[i][j] == '1') {
BFS(land, n, m, i, j, visited);
distinctPools++;
}
}
}
return distinctPools;
}
int main() {
int n, m;
cin >> n >> m;
vector<string> land(n);
for (int i = 0; i < n; i++) {
cin >> land[i];
}
int distinctPools = countDistinctPools(land, n, m);
cout << distinctPools << endl;
return 0;
}