转载:https://blog.csdn.net/fanxing1/article/details/6310037
#include <iostream>
#include<cstdio>
using namespace std;
int Map[20][20],sort_step,X,Y,b_x,b_y;
int Move[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
void get_map()
{
sort_step = INT_MAX;
for(int i=0;i<X;++i)
{
for(int t=0;t<Y;++t)
{
cin>>Map[i][t];
if(Map[i][t]==2)
{
b_x=i;
b_y=t;
}
}
}
}
void dfs(int s_x,int s_y,int step)
{
if(step>=10)
return;
for(int i =0;i<4;++i)
{
int x = s_x;
int y = s_y;
while (1)
{
x+=Move[i][0];
y+=Move[i][1];
if(x>=X||x<0||y<0||y>=Y)
break;
if(Map[x][y]==3)
{
sort_step = min(sort_step,step+1);
return;
}
else if(Map[x][y]==1)
{
if(x-Move[i][0]!=s_x||y-Move[i][1]!=s_y)
{
Map[x][y]=0;
dfs(x-Move[i][0],y-Move[i][1],step+1);
Map[x][y]=1;
}
break;
}
}
}
}
int main()
{
while(cin>>Y>>X&&X&&Y)
{
get_map();
dfs(b_x,b_y,0);
if(sort_step==INT_MAX)
printf("-1\n");
else
printf("%d\n",sort_step);
}
}