原题:
定义一个二维数组:
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
左上角到右下角的最短路径,格式如样例所示。
example 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)
这一题和以前的搜索题不同点在于它是过程导向的,需要输出每一步的过程,而之前的搜索题是以结果为导向的,只用输出最后的结果即可。
这时候我们就需要加一个东西
pre[][]数组
这个数组的相当于指针指向前一个数据,因为每一个指针所连接的两个数据的搭配都是唯一的,因此可以有效的从末尾指向开头。
题意往往要求从开头走向末尾,这时候用stack重构一下即可。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<queue>
#include<stack>
#include<algorithm>
#define ll long long
using namespace std;
int map1[5][5];
int vis[5][5];
int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
struct node{
int x;
int y;
};
node pre[5][5];
queue<node>q;
int main()
{
for(int i=0;i<5;i++)
for(int j =0;j<5;j++)
cin>>map1[i][j];
q.push((node){0,0});
while(!q.empty()){
node y = q.front();
q.pop();
for(int i=0;i<4;i++)
{
node next = y;
next.x += dir[i][0];
next.y += dir[i][1];
if(next.x<5&&next.x>=0&&next.y<5&&next.y>=0&&vis[next.x][next.y]==0&&map1[next.x][next.y]==0)
{
vis[next.x][next.y]=1;
q.push(next);
pre[next.x][next.y] = y;
}
}
}
// cout<<pre[4][4].x<<pre[4][4].y<<"yes"<<endl;
stack<node>so;
so.push((node){4,4});
while(1){
node k = so.top();
// cout<<pre[k.x][k.y].x<<endl;
if(pre[k.x][k.y].x==0&&pre[k.x][k.y].y==0) break;
so.push(pre[k.x][k.y]);
}
cout<<"(0, 0)"<<endl;
while(!so.empty()){
node s = so.top();
so.pop();
cout<<'('<<s.x<<","<<" "<<s.y<<')'<<endl;
}
}