EOJ 1224 bfs

#include<bits/stdc++.h>
using namespace std;

typedef pair<int,int> pii;
const int maxN=220;
const int inf=1e9;

char G[maxN][maxN];

int M,N;
int cnt[maxN][maxN];

const int tx[]={-1,0,1,0},ty[]={0,1,0,-1};

int bfs(pii s){
    for(int i=0;i<maxN;i++){
        for(int j=0;j<maxN;j++)cnt[i][j]=inf;
    }
    cnt[s.first][s.second]=0;
    queue<pii> q;
    pii p;
    int a,b,res=inf;
    q.push(s);
    while(!q.empty()){
        p=q.front();
        q.pop();
        for(int i=0;i<4;i++){
            a=p.first+tx[i];
            b=p.second+ty[i];
            if(a>=0&&a<N&&b>=0&&b<M&&G[a][b]!='#'){
                if(G[a][b]=='X'&&cnt[p.first][p.second]+2<cnt[a][b]){
                    cnt[a][b]=cnt[p.first][p.second]+2;
                    q.push(pii(a,b));
                }else if(G[a][b]!='X'&&cnt[p.first][p.second]+1<cnt[a][b]){
                    cnt[a][b]=cnt[p.first][p.second]+1;
                    if(G[a][b]!='T')q.push(pii(a,b));
                    else res=min(res,cnt[a][b]);
                }
            }
        }
    }
    return res;
}

int main(){
    while(~scanf("%d%d",&N,&M)){
        memset(G,0,sizeof(G));
        for(int i=0;i<N;i++)scanf("%s",G[i]);
        pii s;
        for(int i=0;i<N;i++){
            for(int j=0;j<M;j++)if(G[i][j]=='S'){
                s=pii(i,j);
                goto here;
            }
        }
        here:
        int res=bfs(s);
        if(res<inf)printf("%d\n",res);
        else printf("impossible\n");
    }
}

猜你喜欢

转载自www.cnblogs.com/TAMING/p/9344587.html
BFS