Description
一个球只能走直线,且只能在碰到石头的时候才能停下来,而被碰到的石头将会消失,走一次直线只算一步,求最少步数
Input
多组用例,每组用例第一行为两个整数w和h表示区域的宽度和高度,之后为一h*w矩阵,其中0表示空格,1表示石头,2表示起点,3表示终点,以0 0结束输入
Output
对于每组用例,输出球从起点到终点的最少步数,如果行动时超出方格的界限或步数超过了10直接输出-1
Sample Input
2 1
3 2
6 6
1 0 0 2 1 0
1 1 0 0 0 0
0 0 0 0 0 3
0 0 0 0 0 0
1 0 0 0 0 1
0 1 1 1 1 1
6 1
1 1 2 1 1 3
6 1
1 0 2 1 1 3
12 1
2 0 1 1 1 1 1 1 1 1 1 3
13 1
2 0 1 1 1 1 1 1 1 1 1 1 3
0 0
Sample Output
1
4
-1
4
10
-1
Solution
dfs搜索所有可能路径找出最小步数
剪枝:
1,步数大于10直接退出搜索
2,跑到区域外则停止搜索
Code
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<functional>
using namespace std;
const int Max=30;
int map[Max][Max];
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;
if(step>10)//步数大于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)//无法到达终点
cout<<"-1"<<endl;
else//可以到达终点则输出最小步数
cout<<minStep<<endl;
}
return 0;
}