#include <stdio.h>
#include <algorithm>
using namespace std;
int map[30][30];
int dir[4][2] = {{-1,0},{0,-1},{1,0},{0,1}};
int flag;
int minStep;
int w,h;
void dfs(int x, int y, int step)
{
int nx,ny;
int tx,ty;
int px,py;
if(step > 10)return;
if(map[x][y] == 3)
{
minStep = min(minStep, step);
return;
}
for(int i=0; i<4; i++)
{
tx = x + dir[i][0];
ty = y + dir[i][1];
nx = x;
ny = y;
while(tx >= 0 && tx < h && ty >= 0 && ty < w && map[tx][ty] != 1)
{
nx += dir[i][0];
ny += dir[i][1];
if(map[nx][ny] == 3)
{
minStep = min(minStep, step);
return;
}
tx = nx + dir[i][0];
ty = ny + dir[i][1];
if(tx < 0 || tx >= h || ty < 0 || ty >= w)
break;
if(map[tx][ty] == 1)
{
map[tx][ty] = 0;
dfs(nx, ny, step+1);
map[tx][ty] = 1;
}
}
}
}
int main()
{
int sx,sy;
while(scanf("%d %d",&w,&h) != EOF && w != 0 && h != 0)
{
minStep = 10000;
for(int i=0; i<h; i++)
{
for(int j=0; j<w; j++)
{
scanf("%d",&map[i][j]);
if(map[i][j] == 2)
{
sx = i;
sy = j;
}
}
}
dfs(sx, sy, 1);
if(minStep == 10000) printf("-1\n");
else printf("%d\n",minStep);
}
return 0;
}
POJ3009
最新推荐文章于 2020-05-02 10:22:49 发布