2020-09-12

简单的一刀dfs,每次把条件改为一路走到底就行了

参考的博客https://www.cnblogs.com/sky-stars/p/11182542.html

#include<iostream>
#include<algorithm>
#include<cstring>

using namespace std;

const int MAXN=25;

int sx,sy,ex,ey;
int ans;
int w,h;
int map[MAXN][MAXN];

int dt[][2]={{1,0},{-1,0},{0,1},{0,-1}};

void dfs(int x,int y,int step) //在(x, y)位置时前面已经走了step步
{
    if(x==ex&&y==ey)//当前所在的点就是终点
    {
        if(step<ans)//看看有没有比以前更少的步数
            ans=step;
        return;
    }
    if(step==10||step>=ans)//若超过10步,或超过当前最少步数直接结束
        return;
    for(int i=0; i<4; i++)//四个方向搜索
    {
        int tx=dt[i][0]+x;
        int ty=dt[i][1]+y;
        while(tx>=0&&tx<h&&ty>=0&&ty<w&&map[tx][ty]!=1)//若此方向能走,则走到尽头,直至出场或撞墙
        {
            if(tx==ex&&ty==ey)//若在过程中到达目标点
            {
                step++;
                if(step<ans)
                    ans=step;
                return;
            }
            tx+=dt[i][0];
            ty+=dt[i][1];
        }
        if((tx==x+dt[i][0]&&ty==y+dt[i][1])||tx<0||tx>=h||ty<0||ty>=w)//此方向不能走,或出场
            continue;
        map[tx][ty]=0;//撞墙
        step++;
        dfs(tx-dt[i][0],ty-dt[i][1],step);//这里要减当前方向一格,因为撞墙是要停在墙前而不是呆在被撞的墙的位置格
        step--;//回溯
        map[tx][ty]=1;
    }
}
int main()
{
    while(cin>>w>>h,w+h)
    {
        ans=11;//初始化
        memset(map,0,sizeof(map));
        for(int i=0; i<h; i++)
            for(int j=0; j<w; j++)
            {
                cin>>map[i][j];
                if(map[i][j]==2)//记录起点
                {
                    sx=i;
                    sy=j;
                    map[sx][sy]=0;
                }
                if(map[i][j]==3)//记录终点
                {
                    ex=i;
                    ey=j;
                }
            }
        dfs(sx,sy,0);//搜索
        if(ans==11)
            cout<<-1<<endl;
        else
            cout<<ans<<endl;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值