#include
#include
#include
using namespace std;
int q , p ;
int a [20][20] , book[20][20];
int minx = 999;
int next1[4][2] = { {0,1}, //向右走
{1,0}, // 向下走
{0,-1}, //向左走
{-1,0} } ;//向上走
void dfs(int a1, int a2, int a3, int a4, int step)
{
if ( a1 == a3 && a2 == a4)
{
if ( step < minx ) minx = step ;
return ;
}
int k, tx, ty;
for ( k = 0 ; k<=3 ; k++)
{
tx = a1+next1[k][0];
ty = a2+next1[k][1];
//判断是否越界
if ( tx<0 || tx>=q || ty<0 || ty>=p )
continue ;
if ( a[tx][ty] == 0 && book[tx][ty] == 0)
{
book[tx][ty]=1; //标记这个点已经走过,以减少for循环的次数,提高效率
dfs(tx,ty,a3,a4,step+1);
book[tx][ty] = 0 ;
}
}
return ;
}
int main()
{
scanf("%d %d",&q,&p);// q为行,p为列
getchar();
for ( int i = 0 ; i < q ; i++ )
{
for ( int j = 0 ; j < p ; j++ )
{ char l;
scanf("%c",&l);
if ( l=='*') a[i][j] = 0 ;
else a[i][j]=1;}
getchar();
}
int a1,a2,a3,a4;
scanf("%d %d %d %d",&a1,&a2,&a3,&a4);
//cout << a1 << ' ' << a2 << ' ' << a3 << ' ' << a4 << endl;
dfs(a1,a2,a3,a4,0);
cout << minx << endl ;
}
本关任务:给定一个大小为N×M的迷宫地图,迷宫有通道*和墙壁#,每一步可以向邻接的上下左右四个方向的通道移动,墙壁不可通过。给定起点和终点坐标,求解从起点(x1,y1)到终点(x2,y2)所需的最小步数,若无解则输出0。
测试输入:
4 5
#
#
#
#
0 4
3 0