#include <iostream>
using namespace std;
#define N 22
int initial[N][N];
int w,h,success,step=0;
int start[2],des[2],n=1,mlength=10;
int dirx[4]={0,1,0,-1},diry[4]={1,0,-1,0};
void DFS(int x,int y,int step)
{
//cout << "第" << step << "步:" << x << "," << y << endl;
if(step>=mlength)//进行剪枝
return;
for (int i=0;i<=3;i++)
{
int px=x+dirx[i],py=y+diry[i];
if(initial[px][py]==1)
continue;
while(initial[px][py]==0||initial[px][py]==2)
{
px=px+dirx[i];
py=py+diry[i];
}
if(px>=0&&px<h&&py>=0&&py<w)
{
if(px==des[0]&&py==des[1])
success=1;
else
{
initial[px][py]=0;
DFS(px-dirx[i],py-diry[i],step+1);
initial[px][py]=1;//回溯
}
}
if(success)
{
success=0;
if(step<mlength)
mlength=step;
}
}
}
int main()
{
//freopen("in.txt","r",stdin);
memset(initial,0,sizeof(initial));
cin >> w >> h;
while (w&&h)
{
step=1;
mlength=11;
for (int i=0;i<h;++i)
{
for (int j=0;j<w;++j)
{
cin >> initial[i][j];
if(initial[i][j]==2)
{
start[0]=i;
start[1]=j;
}
else if(initial[i][j]==3)
{
des[0]=i;des[1]=j;
}
}
}
DFS(start[0],start[1],1);
if(mlength>10) cout << "-1" << endl;
else cout << mlength << endl;
cin >> w >> h;
}
return 0;
}
poj3009
最新推荐文章于 2022-04-11 10:34:52 发布