问题 c: 队列求迷宫

在这里插入图片描述
如图所示,迷宫的入口为(1,1),出口为(8,8)。用队列求迷宫
int main(){
int ma[111][111]={//设置迷宫数组
{1,1,1,1,1,1,1,1,1,1},
{1,0,0,1,0,0,0,1,0,1},
{1,0,0,1,0,0,0,1,0,1},
{1,0,0,0,0,1,1,0,0,1},
{1,0,1,1,1,0,0,0,0,1},
{1,0,0,0,1,0,0,0,0,1},
{1,0,1,0,0,0,1,0,0,1},
{1,0,1,1,1,0,1,1,0,1},
{1,1,0,0,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1}
};

#include<bits/stdc++.h>
using namespace std;
#define maxn 10010
struct dot{
	int x;
	int y;
	int pre;
}temp;
queue<dot>q;
stack<dot>s,s1;
int dir[4][2]={-1,0,0,-1,1,0,0,1};
int main()
{
	freopen("input.txt","r",stdin);
	//freopen("output.txt","w",stdout);
	int ma[111][111]={//设置迷宫数组
		{1,1,1,1,1,1,1,1,1,1},
		{1,0,0,1,0,0,0,1,0,1},
		{1,0,0,1,0,0,0,1,0,1},
		{1,0,0,0,0,1,1,0,0,1},
		{1,0,1,1,1,0,0,0,0,1},
		{1,0,0,0,1,0,0,0,0,1},
		{1,0,1,0,0,0,1,0,0,1},
		{1,0,1,1,1,0,1,1,0,1},
		{1,1,0,0,0,0,0,0,0,1},
		{1,1,1,1,1,1,1,1,1,1},
	};
	dot start,t; 
	int xe=8;
	int ye=8; 
	start.x=1;
	start.y=1;
	start.pre=1;
	ma[start.x][start.y]=-1;
	q.push(start);
	while(q.back().x!=xe||q.back().y!=ye){
		start=q.front();
		s.push(start);
		q.pop();
		for( int i=0; i<4; i++ ){
			dot ans;
			ans.x=start.x+dir[i][0];
			ans.y=start.y+dir[i][1];
			if(ma[ans.x][ans.y]==0){
				ans.pre=start.pre+1;
				q.push(ans);
				ma[ans.x][ans.y]=-1;
			}
		}
	}
	while(!q.empty()){
		start=q.front();
		q.pop();
		s.push(start);
	}
//	temp.x=8;temp.y=8;temp.pre=0;
//	s1.push(temp);
	int ansx=8,ansy=8,cnt=s.top().pre-1;
	while(cnt!=1){
		temp=s.top();
		if(temp.pre!=cnt) s.pop();
		else if(temp.pre==cnt&&(temp.x==ansx&&abs(temp.y-ansy)==1||temp.y==ansy&&abs(temp.x-ansx)==1)){
			s1.push(temp);
			cnt=temp.pre-1;
			ansx=temp.x;ansy=temp.y;
		}
		else s.pop();
	}
//	temp.x=1;temp.y=1;temp.pre=0;
//	s1.push(temp);
	while(!s1.empty()){
		temp=s1.top();
		s1.pop();
		cout<<temp.x<<' '<<temp.y<<'\n';
	}
	return 0;
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值