迷宫问题
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 15775 | Accepted: 9389 |
Description
定义一个二维数组:
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
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)
参考解救人质的代码,写出这个不难,关键是有路径的回溯,用递归即可,关键要设置一个跳出递归的条件
#include <stdio.h>
#include <iostream>
#include <cstring>
using namespace std;
int a[51][51]={0};
int book[51][51]={0};
struct node
{
int x;
int y;
int f;
int s;
}que[2501];
void print(int q){
if(que[q].f!=0){ //一开始没有设置条件,结果一直回溯,无法退出,没有输出结果
print(que[q].f); //回溯到上一个father,这样一直不断回溯,直到f=0,退回f=1的最近递归处,也就是下一行,打印,f=1的调用结束,退回f=2的最近一次递归处.....
printf("(%d, %d)",que[q].x,que[q].y);
cout<<endl;
}
}
int main()
{
int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
int head,tail;
int i,j,k,start_x,start_y,p,q,tx,ty,flag;
// int n,m;
// cin>>n>>m;
// for(i=0;i<n;i++)
// for(j=0;j<m;j++)
// cin>>a[i][j];
for(i=0;i<=4;i++)
for(j=0;j<=4;j++)
scanf("%d",&a[i][j]);
start_x=0;
start_y=0;
head=1;
tail=1;
que[tail].x=start_x;
que[tail].y=start_y;
que[tail].f=0;//对应上面回溯的条件
que[tail].s=0;
tail++;
book[start_x][start_y]=1;
flag=0;
printf("(0, 0)\n");
while(head<tail){
for(k=0;k<=3;k++){
tx=que[head].x+next[k][0];
ty=que[head].y+next[k][1];
if(tx<0||tx>4||ty<0||ty>4)
continue;
if( a[tx][ty]==0&&book[tx][ty]==0)
{
book[tx][ty]=1;
que[tail].x=tx;
que[tail].y=ty;
que[tail].f=head;
// que[tail].s=que[head].s+1;
tail++;
}
if(tx==4&&ty==4){
print(head);
//cout<<head;
flag=1;
break;
}
}
if(flag)
break;
head++;
}
printf("(4, 4)");
return 0;
}
此题为搜索基础题,有时间再用DFS做一下吧!