#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
int n, m, step;
int qx, qy, zx, zy;
int mp[27][27];
int mans=9999999;
void dfs(int x, int y)
{
int i,xx,yy;
if(step >= 10 || step >= mans)
return ;
for(i = 0; i < 4; i++)
{
xx = x;
yy = y;
while(1)
{
xx = xx+dx[i];
yy = yy+dy[i];
if(xx < 0 || yy < 0 || xx>=n||yy >= m)
break;
if(xx == zx && yy == zy)
{
step++;
if(step < mans)
mans = step;
step--;
return;
}
else if(mp[xx][yy]==1)
{
if(xx-dx[i]!=x||yy-dy[i]!=y)
{
step++;
mp[xx][yy] = 0;
dfs(xx-dx[i],yy-dy[i]);
step--;
mp[xx][yy] = 1;
}
break;
}
}
}
}
int main()
{
while(~scanf("%d%d",&m,&n)&&(n+m))
{
int i, j;
step = 0;
mans = 999999;
for(i = 0; i < n; i++)
{
for(j = 0; j < m; j++)
{
scanf("%d",&mp[i][j]);
if(mp[i][j] == 2)
{
qx = i;
qy = j;
}
if(mp[i][j]==3)
{
zx = i;
zy = j;
}
}
}
mp[qx][qy]=0;
dfs(qx,qy);
if(mans == 999999)
printf("-1\n");
else
printf("%d\n",mans);
}
return 0;
}
POJ-3009-Curling 2.0- DFS
最新推荐文章于 2020-05-02 10:22:49 发布