题目大意:
定义一个二维数组:
int maze[5][5] = { 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, };
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。输入一个由0或1组成的5*5矩阵,输出最佳路径;
基本思路:经典DFS,注意开另外一个数组用于储存当前最短路径;注意判断条件;
代码如下:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxn = 100;
int book[maxn][maxn];//是否访问过
int maps[maxn][maxn];//储存地图
int minstep=1<<30;
int best[maxn][2];//当前最优路径
int way[maxn][2];//当前路径
int dr[]={-1,1,0,0};
int dc[]={0,0,-1,1};
void dfs(int x,int y,int step)
{
if(x==4&&y==4)
{
if(step<minstep)
{
minstep=step;
for(int i=0;i<step;++i)
{
best[i][0]=way[i][0];
best[i][1]=way[i][1];
}
}
return;
}
for(int i=0;i<=3;++i)
{
int xx=x+dr[i];
int yy=y+dc[i];
if(xx<0||xx>4||yy<0||yy>4||book[xx][yy]==1||maps[xx][yy]==1) continue;
way[step][0]=xx;
way[step][1]=yy;
book[xx][yy]=1;
dfs(xx,yy,step+1);
book[xx][yy]=0;
}
return;
}
int main()
{
for(int i=0;i<5;++i)
for(int j=0;j<5;++j)
cin>>maps[i][j];
memset(book,0,sizeof(book));
dfs(0,0,1);
for(int i=0;i<minstep;++i)
cout << '(' << best[i][0] << ", " << best[i][1] << ')' << endl;
}
测试数据:
Sample Input
0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 0
Sample Output
(0, 0) (1, 0) (2, 0) (2, 1) (2, 2) (2, 3) (2, 4) (3, 4) (4, 4)