#include<iostream>
using namespace std;
int w,h,min1;
int s[25][25],map[50];
int to[4][2]={0,-1,0,1,-1,0,1,0};
void dfs(int x,int y,int cnt)
{
int i,xx,yy;
if(cnt>10) return;
for(i=0;i<4;i++)
{
xx=x+to[i][0];
yy=y+to[i][1];
while(xx>=0&&xx<h&&yy>=0&&yy<w&&s[xx][yy]==0)//一直沿着该方向找下去
{
xx+=to[i][0];
yy+=to[i][1];
}
if(xx>=0&&xx<h&&yy>=0&&yy<w)//否则进行判断
{
if(s[xx][yy]==1)
{
if(xx-to[i][0]==x&&yy-to[i][1]==y)
continue;//所抛的位置和1相邻,则放弃此次尝试
s[xx][yy]=0;
dfs(xx-to[i][0],yy-to[i][1],cnt+1);
s[xx][yy]=1;//回溯,重置障碍物
}
else if(s[xx][yy]==3)
{
if(cnt<min1)min1=cnt;//记录最少步数
return;
}
}
}
}
int main()
{
while(cin>>w>>h&&w&&h)
{
int i,j,a,b;
for(i=0;i<h;i++)
for(j=0;j<w;j++)
{
cin>>s[i][j];
if(s[i][j]==2)
{ a=i,b=j;}
}
s[a][b]=0;
min1=11;
dfs(a,b,1);
if(min1<11)
cout<<min1<<endl;
else cout<<-1<<endl;
}
return 0;
}
poj3009DFS
最新推荐文章于 2020-05-02 10:22:49 发布