codeforces329B(bfs)

时间:2022-07-28
本文章向大家介绍codeforces329B(bfs),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题意描述

给定RxC的网格,网格中存在猎人,询问走到终点前要和多少组猎人碰面

思路

由于猎人事先知道我们行走的路线,所以猎人们可以先走到终点前等待,可以使用bfs预处理出终点到各个点之间的距离,如果猎人到终点的距离小于等于我们从起点到终点的距离,那么一点可以相遇,最后遍历一遍即可。

代码

#include<bits/stdc++.h>
#define x first
#define y second
#define IOS ios::sync_with_stdio(false);cin.tie(0);
using namespace std;
typedef unsigned long long ULL;
typedef pair<int,int> PII;
typedef pair<long,long> PLL;
typedef pair<char,char> PCC;
typedef long long LL;
const int N=1010;
const int M=150;
const int INF=0x3f3f3f3f;
const int MOD=998244353;
char g[N][N];
int d[N][N];
int n,m,stx,sty,edx,edy;
int dx[4]={0,1,-1,0},dy[4]={1,0,0,-1};
void bfs(){
    queue<PII> q;
    memset(d,INF,sizeof d);
    d[edx][edy]=0;
    q.push({edx,edy});
    while(q.size()){
        PII t=q.front();q.pop();
        for(int i=0;i<4;i++){
            int gx=t.x+dx[i],gy=t.y+dy[i];
            if(gx>=0 && gy>=0 && gx<n && gy<m && d[gx][gy]==INF && g[gx][gy]!='T'){
                d[gx][gy]=d[t.x][t.y]+1;
                q.push({gx,gy});
            }
        }
    }
}
void solve(){
    cin>>n>>m;
    for(int i=0;i<n;i++) cin>>g[i];
    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
            if(g[i][j]=='S'){
                stx=i;
                sty=j;
            }
            if(g[i][j]=='E'){
                edx=i;
                edy=j;
            }
        }
    }
    bfs();
    int res=d[stx][sty];
    int ans=0;
    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
            if(d[i][j]<=res && g[i][j]>'0' && g[i][j]<='9'){
                ans+=g[i][j]-'0';
            }
        }
    }
    cout<<ans<<endl;
}
int main(){
    IOS;
    solve();
    return 0;
}