栈的应用--迷宫

#include<stdio.h>
#include<stack>
#include<stdlib.h>
#define MAXMATRIXSIZE 100
#define MAXSTACKSIZE 100
using namespace std;
stack <struct MazePosition> s;
struct offsets{
	short int vert;
	short int horiz;
}; 

struct MazePosition{
	short int row;//当前行 
	short int col;//当前列 
	short int dir;//下一方向的序号 
};

void path(int maze[][MAXMATRIXSIZE],int exitrow,int exitcol)
{
	struct offsets move[8]={{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1}};
	int mark[MAXMATRIXSIZE][MAXMATRIXSIZE]={0};
	int i;
	struct MazePosition p;
	short int row,col,nextrow,nextcol,dir;
	bool found=false;
	
	mark[exitrow][exitcol]=1;//走过的标记,路径不能重复了 
	p.row=exitrow;
	p.col=exitcol;
	p.dir=0; 
	s.push(p);
	
	while(!s.empty()&&!found)
	{
		p=s.top();
		s.pop();
		row=p.row;col=p.col;dir=p.dir;
		while(dir<8&&!found)
		{
			nextrow=row+move[dir].vert;
			nextcol=col+move[dir].horiz;
			if(nextrow==1&&nextcol==1) found=true;  //如果到达出口
			else 
			{
				if(!maze[nextrow][nextcol]&&!mark[nextrow][nextcol])
				{
					mark[nextrow][nextcol]=1;
					p.row=row;p.col=col;p.dir=dir+1;
					s.push(p);
					row=nextrow;col=nextcol;dir=0;
				 }
				 else ++dir;
			 } 
		}
		if(found)
		{
			printf("找到路径如下\n");
			printf("行 列\n");
			printf("1  1\n");
			printf("%d %d\n",row,col);
			while(!s.empty())
			{
				p=s.top();
				s.pop();
				printf("%d %d\n",p.row,p.col);
			 } 
		}
		else
		printf("无解"); 
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值