一块石头开始处于S处,可以朝四个方向移动,但是当与它相邻的是阻碍物的时候就无法从那个方向进行移动,当朝一个方向移动时,遇到障碍物就停止,并且那个障碍物消失,该石头停在撞那个障碍物之前的那个方格里面,题目问的是最少应该是移动几次石头到达终点G,如果最少移动次数超过了10,就代表无法到达,输出-1,
也会出现无法到达G处,输出-1;
当朝着一个方向直接冲出了这个地图,就代表那个方向的移动时失败的,是无法到达终点的。
懂意思之后,实现起来就简单了。
具体看代码
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int dir[][2]={{1,0},{0,1},{-1,0},{0,-1}};
int row,col;
int map[21][21];
bool flag[21][21];
int sx,sy,ex,ey;
int minS;
void dfs(int x,int y,int step)
{
if(step>10)
{
return;
}
if(x==ex && y==ey)
{
if(step<minS)
{
minS=step;
}
return;
}
int i;
for(i=0;i<4;i++)
{
int xx=x+dir[i][0];
int yy=y+dir[i][1];
if(xx>row || xx<1 || yy>col || yy<1 || map[xx][yy]==1)
{
continue;
}
if(map[xx][yy]==3)
{
dfs(xx,yy,step+1);
continue;
}
bool ff1=false,ff2=false;
while(map[xx][yy]==0)
{
xx+=dir[i][0];
yy+=dir[i][1];
if(xx<1 || xx>row || yy<1 || yy>col)
{
ff1=true;
break;
}
if(map[xx][yy]==3)
{
dfs(xx,yy,step+1);
ff2=true;
}
}
if(ff1 || ff2)
{
continue;
}
int x1=xx-dir[i][0];
int y1=yy-dir[i][1];
map[xx][yy]=0;
dfs(x1,y1,step+1);
map[xx][yy]=1;
}
}
int main()
{
while(~scanf("%d%d",&col,&row))
{
if(col==0 && row==0)
{
break;
}
int i,j;
for(i=1;i<=row;i++)
{
for(j=1;j<=col;j++)
{
scanf("%d",&map[i][j]);
if(map[i][j]==2)
{
sx=i;
sy=j;
map[i][j]=0;
}
if(map[i][j]==3)
{
ex=i;
ey=j;
}
}
}
minS=11;
dfs(sx,sy,0);
if(minS==11)
{
printf("-1\n");
}
else
{
printf("%d\n",minS);
}
}
return 0;
}