这题用广度优先搜索
2024-08-20 10:29:05
发布于:广东
3阅读
0回复
0点赞
#include <bits/stdc++.h>
using namespace std;
const int N = 120;
int n, m;
int ans = 0;
char a[N][N];
int dx[8] = {-1, -1, -1, 0, 0, 1, 1, 1};
int dy[8] = {-1, 0, 1, -1, 1, -1, 0, 1};
bool vis[N][N];
struct node{
int x, y;
}l, r;
void bfs(int x, int y){
queue<node> q;
q.push({x, y});
vis[x][y] = 1;
while(q.size()){
l = q.front();
q.pop();
for(int i = 0; i < 8; i++){
int nx = l.x + dx[i];
int ny = l.y + dy[i];
if(nx >= 1 && ny >= 1 && nx <= n && ny <= m && !vis[nx][ny] && a[nx][ny] == 'W'){
vis[nx][ny] = 1;
q.push({nx, ny});
}
}
}
}
int main(){
cin >> n >> m;
memset(vis, 0, sizeof vis);
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
cin >> a[i][j];
}
}
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
if(a[i][j] == 'W' && !vis[i][j]){
bfs(i, j);
ans++;
}
}
}
cout << ans;
return 0;
}
这里空空如也
有帮助,赞一个