定义一个二维数组:
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表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
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)
题意描述:
给一个5*5的矩阵打印出从(0,0)这个点到(4,4)这个点的最短路径。
解释:
为什么要用两次dfs呢?
因为dfs在找最短路时是把所有的点全部遍历一遍,因此就会出现明明已经找到最短的道路了,
可是点还没有遍历完,因此后几个点的坐标就会出现错误,所以才需要用两次dfs。第一个找最短路,第二个打印路径。
AC代码:
#include<stdio.h>
#include<string.h>
int min=99999999,flag=0;
int next[4][2]={1,0, -1,0, 0,-1, 0,1};
int a[10][10],b[25],c[25],book[10][10];
//找出最短路径
void dfs1(int x,int y,int step)
{
int k,tx,ty;
if(x==4&&y==4){
if(min>step)
min=step;
return ;
}
for(k=0;k<4;k++){
tx=x+next[k][0];
ty=y+next[k][1];
if(tx<0||ty<0||tx>4||ty>4)
continue;
if(book[tx][ty]==0&&a[tx][ty]==0){
book[tx][ty]=1;
dfs1(tx,ty,step+1);
book[tx][ty]=0;
}
}
}
//打印路径
void dfs(int x,int y,int step)
{
int k,tx,ty;
if(x==4&&y==4){
if(step==min&&flag==0)
{
flag=1;
for(int i=0;i<min;i++)
printf("(%d, %d)\n",b[i],c[i]);
}
return ;
}
for(k=0;k<4;k++){
tx=x+next[k][0];
ty=y+next[k][1];
if(tx<0||ty<0||tx>4||ty>4)
continue;
if(book[tx][ty]==0&&a[tx][ty]==0){
book[tx][ty]=1;
b[step]=tx;c[step]=ty;
dfs(tx,ty,step+1);
book[tx][ty]=0;
}
}
}
int main(void)
{
int i,l,k;
for(i=0;i<5;i++)
for(l=0;l<5;l++){
scanf("%d",&a[i][l]);
book[i][l]=0;
}
for(i=0;i<25;i++)
b[i]=c[i]=0;
book[0][0]=1;
dfs1(0,0,1);
dfs(0,0,1);
return 0;
}