简单的一刀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;
}
}