1. 程式人生 > 其它 >小A與小B(雙向bfs)

小A與小B(雙向bfs)

技術標籤:牛客每日一題

#include <bits/stdc++.h>
#define ll long long
const int maxn = 1010;
using namespace std;
int dx[8]={0,0,1,-1,1,1,-1,-1};
int dy[8]={1,-1,0,0,1,-1,1,-1};
bool visited[2][maxn][maxn];
char maps[maxn][maxn];
int n,m;

struct point{
    int x,y;
    point(int a,int b){x=a,y=b;}
};
queue<point> q[2];
bool bfs(int x){
    int sz=q[x].size();
    while(sz--){
        point temp=q[x].front();
        q[x].pop();
        for(int i=0;i<8-4*x;i++){
            int nx=temp.x+dx[i],ny=temp.y+dy[i];
            if(nx<0||nx>=n||ny<0||ny>=m||maps[nx][ny]=='#') continue;
            if(visited[1-x][nx][ny]) return true;
            if(!visited[x][nx][ny]){
                q[x].push(point(nx,ny));
                visited[x][nx][ny]=true;
            }
        }
    }
    return false;
}
int solve(){
    int res=0;
    while(!q[0].empty()||!q[1].empty()){
        res++;
        if(bfs(0)) return res;
        if(bfs(1)) return res;
        if(bfs(1)) return res;
    }
    return -1;
}

int main()
{
    cin>>n>>m;
    memset(visited,false,sizeof(visited));
    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
            cin>>maps[i][j];
            if(maps[i][j]=='C'){
                q[0].push(point(i,j));
                visited[0][i][j]=true;
            }
            if(maps[i][j]=='D'){
                q[1].push(point(i,j));
                visited[1][i][j]=true;
            }
        }
    }

    int ans=solve();
    if(ans==-1) cout<<"NO"<<endl;
    else{
        cout<<"YES"<<endl;
        cout<<ans<<endl;
    }
    return 0;
}