アルジャーノンのためAcwing1101。花

ステップ

ここに画像を挿入説明

コード

#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
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";
        }
    }
}
公開された175元の記事 ウォンの賞賛1 ビュー4244

おすすめ

転載: blog.csdn.net/weixin_45080867/article/details/104091778