#include<iostream>
#include<cstdlib>
#include<utility>
#include<cstdio>
using namespace std;
// 1.坐标位置使用 pair 记录
typedef pair<int,int> pii;
int maze[15][15]={0};
// 2.迷宫类型
struct mazeEle{//迷宫的一个格子单元
int order;//顺序,第几个走的
pii seat;//位置
int direction;
};
typedef struct mazeEle mazeElement;
//3. 储存走过了的迷宫的栈
struct mazestack{
mazeElement *x;
int top;
int stacksize;
};
typedef struct mazestack sstack;
void initstack(sstack* s)//初始化栈
{
s->x = (mazeElement*)malloc(sizeof(mazeElement)*150);
s->top = 0;
s->stacksize = 150;
}
void push_stack(sstack* s,mazeElement e)
{//入栈,注意入栈时对原迷宫进行处理代表已经走过?
if(s->top >= s->stacksize)
{
printf("problem\n");
}
s->x[s->top] = e;
s->top ++;
maze[e.seat.first][e.seat.second] = 3;
}
void pop_stack(sstack* s,mazeElement* e)
{//出栈,//回溯,回到初始状态
*e = s->x[s->top-1];
s->top --;
maze[e->seat.first][e->seat.second] = 0;// return don't passed
}
int can_pass(pii x)
{//!!!!!!!!!!!不是墙 也不是这条路上的??设定!!! 路上设为3 pop时注意修改
int judge=0,pos = maze[x.first][x.second];
if(pos==1 || pos==3)//墙或走过就不能通过
{
judge = 0;
}
else {//否则可以通过
judge = 1; // can pass!!!
}
return judge;
}
void footprint(int curstep, pii x)
{//打印出路径便于调试
// maze[x.first][x.second] = 3;// have passed
// printf("bu %d %d%d ",curstep,x.first,x.second);
}
void initmazeEle(mazeElement* e,int curstep,pii curpos,int dir)
{//对迷宫格的信息进行处理
e->order = curstep;
e->seat = curpos;
e->direction = dir;
//printf("add 1 ");
}
pii nextPos(pii curpos,int dir)
{
if(dir == 1)
{
curpos.second ++; // east
}
else if(dir == 2)
{
curpos.first ++; // south
}
else if(dir == 3)
{
curpos.second --;// west
}
else if(dir == 4)
{
curpos.first --;
}
return curpos;
}
void markprint(pii pos)
{
maze[pos.first][pos.second] = 1;
}
void mazePath(sstack *s,pii start,pii end)
{// 最后直接打印。 关于留下足迹问题:走过有用?
// 关于存储 的问题
pii curpos = start;
int curstep = 1;
mazeElement e;
do{
if(can_pass(curpos))
{
footprint(curstep,curpos);//打印已走路径
initmazeEle(&e,curstep,curpos,1);//e -> 当前位置的第几块 / 位置 / 方向
push_stack(s,e);
if(curpos == end)
{//如果到终点则结束
return;
}
curpos = nextPos(curpos,1);//下一格
curstep++;
}
else{// can't pass
if(s->top!=0)// 非空
{
pop_stack(s,&e);// pop 并 取出
while(e.direction==4 && s->top>0)
{//四个方向都不通,直接设置的 000
markprint(e.seat);// set maze -> 1
pop_stack(s,&e);
}
if(e.direction<4)
{
e.direction ++ ;
push_stack(s,e);
curpos = nextPos(e.seat,e.direction);
}
}
}
}
while(s->top != 0);
}
int main()
{
int n;
cin>>n;
for(int i=0;i<n;i++)//输入迷宫
for(int j=0;j<n;j++)
{
cin>>maze[i][j];// 0 通路 1障碍
}
pii start,end;
start.first = 1;
start.second = 1;
end.first = n-2;
end.second = n-2;
sstack s;
mazeElement temp;
initstack(&s);
mazePath(&s,start,end);
if(s.top == 0)
{
printf("NO");
return 0;
}
for(int i=0;i<s.top;i++)
{
printf("(%d,%d)",s.x[i].seat.first,s.x[i].seat.second);
}
return 0;
}
非递归解决迷宫问题
最新推荐文章于 2023-10-10 20:02:45 发布