模版连通块题
2026-09-11 21:42:21
发布于:浙江
0阅读
0回复
0点赞
#include <bits/stdc++.h>
using namespace std;
int n, m, ans;
char mp[120][120];
int dx[8] = {-1, -1, 0, 1, 1, 1, 0, -1};
int dy[8] = {0, 1, 1, 1, 0, -1, -1, -1};
bool inmap(int x, int y) {
return x >= 1 && x <= n && y >= 1 && y <= m;
}
void bfs(int sx, int sy) {
queue<pair<int, int>> q;
q.push({sx, sy});
mp[sx][sy] = '.';
while (!q.empty()) {
auto t = q.front();
q.pop();
int x = t.first;
int y = t.second;
for (int k = 0;k < 8;k++) {
int nx = x + dx[k];
int ny = y + dy[k];
if (!inmap(nx, ny) || mp[nx][ny] != 'W') continue;
q.push({nx, ny});
mp[nx][ny] = '.';
}
}
}
int main() {
cin >> n >> m ;
for (int i = 1;i <= n;i++)
for (int j = 1;j <= m;j++) cin >> mp[i][j];
for (int i = 1;i <= n;i++) {
for (int j = 1;j <= m;j++) {
if (mp[i][j] == 'W') {
bfs(i, j);
ans++;
}
}
}
cout << ans;
}
这里空空如也







有帮助,赞一个