bfs
2025-07-13 17:08:16
发布于:北京
1阅读
0回复
0点赞
#include <bits/stdc++.h>
using namespace std;
#define V vector
#define all0(x) (x).begin(),(x).end()
#define all1(x) (x).begin()+1,(x).end()
#define pb push_back
#define eb emplace_back
#define fi first
#define se second
#define lb lower_bound
#define ub upper_bound
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
typedef long long LL;
typedef pair<int, int> pi;
typedef pair<LL, LL> pl;
const int N = 100 + 20;
const int INF = 0x3f3f3f3f;
const LL INFLL =0x3f3f3f3f3f3f3f3f;
char v[N][N];
int vis[N][N]; //vis的值代表第几天感染,比如1,就是第一天感染的 , 0 就是还没感染
int dx[]={0,1,0,-1};
int dy[]={1,0,-1,0};
queue<pi> q;
int m;
int n;
int k = 0;//感染人数
void bfs(){
while(!q.empty()){
auto t = q.front();
q.pop();
if(vis[t.fi][t.se] == m + 1) break; //如果等于m + 1天,那前面m天的都算完了
for(int i = 0 ; i < 4 ; i++){ //正常bfs
int x = t.fi + dx[i];
int y = t.se + dy[i];
if(x >= 0 && x <= n && y >= 0 && y <= n &&( !vis[x][y]) && v[x][y] =='.'){
vis[x][y] = vis[t.fi][t.se] + 1; //这个感染者会在第几天感染。
q.push({x,y});
if(vis[x][y] <= m)k++; //因为会计算m + 1 天的感染,所以必须感染天数要<=m天
}
}
}
}
void so() {
cin >> n;
for(int i = 1 ; i <= n ; i++ ){
for(int j = 1 ; j <= n ; j++ ){
cin >>v[i][j];
if(v[i][j] == '@'){ // 把第一天感染的存进去
k++;
vis[i][j] = 1;
q.push({i , j}); // 把第一天感染的入队
}
}
}
cin >> m;
bfs();
cout << k;
}
int main() {
IOS
int tt=1;
// cin >> tt;
while (tt--)
so();
}
这里空空如也
有帮助,赞一个