搜索进阶——迷宫问题(带路径的搜索)

原题:
定义一个二维数组: 
       

       
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;
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值