#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("无解");
}
}
栈的应用--迷宫
最新推荐文章于 2021-05-18 10:54:46 发布