【BFS&&优先队列】HDU 1180 诡异的楼梯

 

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1180

 

 

 

设梯子状态 |为0,—为1 利用(初始状态+步数)%2算出当前梯子状态

 

当遇到梯子,若当前不能走过则到对面且步数加2,若当前能走过则到对面且步数加1,利用优先队列进行BFS

 

#include<cstdio>
#include<iostream>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std; 

struct node{
    friend bool operator< (node n1, node n2)
    {
        return n1.step > n2.step;
    }
    int x,y;
    int step;
};

priority_queue<node> q;
int n,m;
char map[220][220];
int vis[220][220];
int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};


bool jud(int x,int y){
    if(x>=0&&x<n&&y>=0&&y<m&&map[x][y]!='*'&&!vis[x][y])    
        return true;
    return false;
}

int bfs(node start){
    while(!q.empty())q.pop();
    node now,next;
    q.push(start);
    int i;
    while(!q.empty()){
        now=q.top();
        q.pop();
        if(map[now.x][now.y]=='T')
               return now.step;
        for(i=0;i<4;++i){
            next.x=now.x+dir[i][0];
            next.y=now.y+dir[i][1];
            
            if(map[next.x][next.y]=='-'||map[next.x][next.y]=='|'){
                int stu=(map[next.x][next.y]=='|')?0:1;//|=0,-=1;
                
                if((now.step+stu)%2==1){//梯子横
                    if(next.x==now.x){//横向走
                        next.step=now.step+1;
                        next.y+=dir[i][1];
                    }else{//纵向走
                        next.step=now.step+2;
                        next.x+=dir[i][0];
                    }
                }else{
                    if(next.x==now.x){//横向走
                        next.step=now.step+2;
                        next.y+=dir[i][1];
                    }else{//纵向走
                        next.step=now.step+1;
                        next.x+=dir[i][0];
                    }
                }

            }
            else
                next.step=now.step+1;
            
            if(!jud(next.x,next.y))continue; 
            vis[next.x][next.y]=1;
            q.push(next);
        }
    }
    return -1;
}
        

int main(){
    int i,j;
    int ans;
    node start;
    while(scanf("%d%d\n",&n,&m)!=EOF){
        ans=-1;
        memset(vis,0,sizeof(vis));
        for(i=0;i<n;++i){
            for(j=0;j<m;++j){
                scanf("%c",&map[i][j]);
            }
            getchar();
        }
        for(i=0;i<n;++i){
            for(j=0;j<m;++j){
                if(map[i][j]=='S'){
                    start.x=i,start.y=j;
                    start.step=0;
                    ans=bfs(start);
                }
            }
        }
       
        printf("%d\n",ans);

    }
    return 0;
}


 

 

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值