【bfs优先队列】POJ 2312


char g[333][333];
int n,m;
struct node{
    int x,y;
    int step;
    friend bool operator <(node a,node b){
        return a.step>b.step;
    }
};
node st,end;
bool vis[333][333];
int d[4][2] = {0,1,0,-1,1,0,-1,0};
int bfs(){
    int i,j,k;
    priority_queue<node> pp;
    st.step = 0;
    vis[st.x][st.y] = 1;
    pp.push(st);
    node cur,next;
    while(!pp.empty()){
        cur = pp.top();
        pp.pop();
        if(g[cur.x][cur.y]=='T'){
            return cur.step;
        }
        for(i=0;i<4;i++){
            int x = cur.x+d[i][0];
            int y = cur.y+d[i][1];
            if(x<0 || y<0 || x>=n || y>=m || vis[x][y])continue;
            vis[x][y] = 1;
            if(g[x][y]=='B'){
                next.x = x;
                next.y = y;
                next.step = cur.step +2;
                pp.push(next);
            }
            if(g[x][y]=='E'){
                next.x = x;
                next.y = y;
                next.step = cur.step+1;
                pp.push(next);
            }
            if(g[x][y]=='T'){
                next.x = x;
                next.y = y;
                next.step = cur.step+1;
                pp.push(next);
            }
        }
    }
    return -1;
}

int main(){
    while(scanf("%d%d",&n,&m) && (n+m)){
        int i,j;
        for(i=0;i<n;i++){
            scanf("%s",g[i]);
            for(j=0;j<m;j++){
                if(g[i][j]=='Y'){
                    st.x = i,st.y = j;
                }
                if(g[i][j]=='T'){
                    end.x = i,end.y = j;
                }
                vis[i][j] = 0;
            }
        }
        int ans = bfs();
        printf("%d\n",ans);
    }
    return 0;
}





















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值