某岛求药AC代码

· · 题解

某岛求药WAAC代码

#include<bits/stdc++.h>
using namespace std;
int qx[1010],qy[1010],qs[1010];
int sx,sy;
int n,m;
char Map[1010][1010];
int ans[1010][1010];
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
void bfs(){
    int h=0,t=0;
    qx[t]=sx;
    qy[t]=sy;
    qs[t++]=0;
    while(h<t){
        for(int i=0;i<=3;i++){
            int tx=qx[h]+dx[i];
            int ty=qy[h]+dy[i];
            if(Map[tx][ty]=='#' || tx<1 || tx>n || ty<1 || ty>m || qs[h]+1>=ans[tx][ty]){
                continue;
            }
            qx[t]=tx;
            qy[t]=ty;
            qs[t++]=qs[h]+1;
            ans[tx][ty]=qs[h]+1;
        }
        h++;
    }
}
int main(){
    int ex,ey;
    while(1){
        cin>>n>>m;
        if(n==0 && m==0){
            break;
        }
        for(int i=1;i<=n;i++){
            for(int j=1;j<=m;j++){
                ans[i][j]=100000;
                cin>>Map[i][j];
                if(Map[i][j]=='@'){
                    sx=i;
                    sy=j;
                }
                if(Map[i][j]=='*'){
                    ex=i;
                    ey=j;
                }
            }
        }
        bfs();
        if(ans[ex][ey]==100000){
            cout<<-1<<endl;
        }
        else{
            cout<<ans[ex][ey]<<endl;
        }
    }
    return 0;
}