hdu 1180 诡异的楼梯

本文介绍了解决HDOJ 1180题目的方法,包括题目分析、BFS算法实现及代码解析。重点在于处理楼梯和走廊的通行逻辑,以及如何优化搜索路径。

hdu   1180   诡异的楼梯            题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1180

                                 

题目分析:题目描述有点不大清晰,需要补充一点,虽然不能在楼梯上停留,但走廊还是可以停留的,比如在楼梯前等一分钟是可以的。其它的都跟普通BFS一样,楼梯需要加判断,判断当前能否直接通过眼前的楼梯,如果不能就等一分钟。需要注意的是楼梯有可能出现在出口前,从楼梯出来就是出口。

code:

#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
char map[30][30];
int m,n,ex,ey,dir[4][2]={1,0,-1,0,0,1,0,-1};
struct node
{
    int x,y,step;
};
bool judge(node no)
{
    int x=no.x,y=no.y;
    return x>=0&&y>=0&&x<m&&y<n&&map[x][y]!='*';
}
bool able(node f,node n)
{
    int sx=f.x,sy=f.y,ex=n.x,ey=n.y;
    int temp=(sx==ex?1:0);
    temp+=map[n.x][n.y]=='-'?1:0;
    temp+=f.step%2?1:0;
    return !(temp%2);
}
int BFS(int x,int y)
{
    queue<node>q;
    node first,next;
    first.x=x;
    first.y=y;
    first.step=0;
    map[first.x][first.y]='*';
    q.push(first);
    while(!q.empty())
    {
        first=q.front();
        q.pop();
        for(int i=0;i<4;i++)
        {
            next.x=first.x+dir[i][0];
            next.y=first.y+dir[i][1];
            if(map[next.x][next.y]=='|'||map[next.x][next.y]=='-')
            {
                if(!able(first,next))
                {
                    next.step=first.step+2;
                }
                else next.step=first.step+1;
                next.x+=dir[i][0];
                next.y+=dir[i][1];
            }
            else next.step=first.step+1;
            if(next.x==ex&&next.y==ey)return next.step;
            if(judge(next))
            {
                //printf("in x==%d y==%d step==%d\n",next.x,next.y,next.step);
                q.push(next);
                map[next.x][next.y]='*';
            }
        }
    }
    return -1;
}
int main()
{
    int i,j,sx,sy;
    while(scanf("%d%d",&m,&n)!=EOF)
    {
        for(i=0;i<m;i++)
        {
            scanf("%s",map[i]);
            for(j=0;j<n;j++)
            {
                if(map[i][j]=='S')sx=i,sy=j;
                if(map[i][j]=='T')ex=i,ey=j;
            }
        }
        printf("%d\n",BFS(sx,sy));
    }
    return 0;
}

PS:该去找剪枝学了…








评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值