栈,队列实现迷宫问题

#include<stdio.h>
#include<iostream>
using namespace std;
int mg[10][10]
{
	{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},
};
//入口(1,1),出口(8,8)
typedef struct 
{	int x;
	int y;
	int pre;
}gezi;

typedef struct
{	gezi way[200];
	int front,rear;
}Path;

void print(Path p,int pos)
{	int end=pos;
	int j,k=pos;
	do
	{	
		j=k;
		k=p.way[k].pre;
		p.way[j].pre=-1;
	}while(k!=0);//容易出错,
	for(int i=0;i<=end;i++)
	{
		if(p.way[i].pre==-1)
			printf("(%d,%d)\n",p.way[i].x,p.way[i].y);
		
		
	}
}

void SearchWay(int xi,int yi,int xe,int ye){
	Path p;
	p.front=p.rear=0;
	p.way[0].x=xi; p.way[0].y=yi; p.way[0].pre=-1;mg[1][1]=-1;//起始位置 
	int tx,ty;
	p.front=-1;
	int di; 
	while(p.front!=p.rear) 
	{	p.front++; 
		tx=p.way[p.front].x;	ty=p.way[p.front].y;
		if(p.way[p.front].x==8&&p.way[p.front].y==8)
		{	printf("///\n");
			//printf("p.front=%d",p.front);
			print(p,p.front);//输出整体路径 
			printf("...............\n");
		        //for(int i=0;i<=p.front;i++)
			//	printf("(%d,%d)\n",p.way[i].x,p.way[i].y);
			return;
		}
		//进行路径搜索
		if(mg[tx-1][ty]==0)
		{	mg[tx-1][ty]=-1;
			p.rear++;
			p.way[p.rear].x=tx-1; p.way[p.rear].y=ty;
			p.way[p.rear].pre=p.front;
			
		}
		if(mg[tx+1][ty]==0)
		{	mg[tx+1][ty]=-1;
			p.rear++;
			p.way[p.rear].x=tx+1; p.way[p.rear].y=ty;
			p.way[p.rear].pre=p.front;	
			
		}
		if(mg[tx][ty+1]==0)
		{	mg[tx][ty+1]=-1;
			p.rear++;
			p.way[p.rear].x=tx; p.way[p.rear].y=ty+1;
			p.way[p.rear].pre=p.front;
			
		}
		if(mg[tx][ty-1]==0) 
		{	mg[tx][ty-1]=-1;
			p.rear++;
			p.way[p.rear].x=tx; p.way[p.rear].y=ty-1;
			p.way[p.rear].pre=p.front;
			
		}
		/*for(di=0;di<4;di++)
		{
			switch(di)
			{
				case 0:tx=p.way[p.front].x-1;ty=p.way[p.front].y;break;
				case 1:tx=p.way[p.front].x+1;ty=p.way[p.front].y;break;
				case 2:tx=p.way[p.front].x;ty=p.way[p.front].y+1;break;
				case 3:tx=p.way[p.front].x;ty=p.way[p.front].y-1;break;
			}
			if(mg[tx][ty]==0)
			{
				p.rear++;
				p.way[p.rear].x=tx; p.way[p.rear].y=ty;
				p.way[p.rear].pre=p.front;
				mg[tx][ty]=-1;
			}
		}*/ 
	}
}

int main(){
	SearchWay(1,1,8,8);
}

在实现过程中遇到的问题有:

1、忘记在迷宫位置入队的时候,将mg[i][j]置为-1,否则将会回溯,导致得不到解;

2、在反向输出迷宫路径的时候,要判断数组下标,元素的pre,和-1之间的关系。正确思路是:

类似链表的free操作,标记下一个元素,释放当前元素,将当前元素赋给下一个元素,如此循环


学习到的东西有:利用swtich操作,简洁代码的重复性。

只需要利用case列出可能取到的路径,再统一用if判断语句进行入队列。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值