Acwing1101. 献给阿尔吉侬的花束

步骤

Acwing1101. 献给阿尔吉侬的花束_第1张图片

代码

#include 
#include 
#include 
#include 
using namespace std;
typedef pair<int, int> PII;
const int N=220;
char g[N][N];
int dist[N][N];
int bfs(int n,int m,PII st,PII ed){
    queue<PII> q;
    memset(dist,-1,sizeof dist);
    q.push(st);
    dist[st.first][st.second]=0;
    int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
    while(q.size()){
        auto t=q.front();
        q.pop();
        for(int i=0;i<4;i++){
            int x=t.first+dx[i];
            int y=t.second+dy[i];
            if(x<1||x>n||y<1||y>m)continue;//出边界
            if(dist[x][y]!=-1)continue;//已经访问
            if(g[x][y]=='#')continue;//不能走
            dist[x][y]=dist[t.first][t.second]+1;
            if(g[x][y]=='E')return dist[x][y];
            q.push({x,y});
        }
    }
    return -1;
}
int main(){
    int t;
    cin >> t ;
    while(t--){
        int n,m;
        cin >> n >> m;
        PII st,ed;
        for(int i=1;i<=n;i++){
            for(int j=1;j<=m;j++){
                cin >> g[i][j];
                if(g[i][j]=='E')ed={i,j};
                if(g[i][j]=='S')st={i,j};
            }
        }
        int ans=bfs(n,m,st,ed);
        if(ans==-1){
            cout << "oop!\n";
        }else{
            cout << ans << "\n";
        }
    }
}

你可能感兴趣的:(BFS,ACwing)