任务:可以输入一个任意大小的迷宫数据,用非递归的方法求出一条走出迷宫的路径,并将路径输出;
要求:在上交资料中请写明:存储结构、基本算法(可以使用程序流程图)、源程序、测试数据和结果、算法的时间复杂度、另外可以提出算法的改进方法;
#include <bits/stdc++.h>
#define row 10
#define col 10
#define Up 0
#define Right 1
#define Down 2
#define Left 3
using namespace std;
typedef struct stacknode//定义栈节点数据类型
{
int x,y;//表示节点位置
int dir;//dir数组表示4个方向,0:上 1:右 2:下 3:左
struct stacknode *next;
} stacknode,*linkstack;
typedef struct Linkstack
{
linkstack top;//定义栈顶
int cnt;//节点数
} Linkstack; //定义链栈数据结构
int mapp[row][col]=
{
{1,1,1,1,1,1,1,1,1,1},
{1,2,1,1,0,0,0,1,0,1},
{1,0,1,1,0,1,1,1,0,1},
{1,0,0,0,0,1,1,0,0,1},
{1,0,1,1,1,0,0,0,1,1},
{1,0,0,0,1,0,1,0,0,1},
{1,0,1,0,0,0,1,0,1,1},
{1,0,1,1,1,0,1,1,1,1},
{1,1,1,1,1,0,0,0,3,1},
{1,1,1,1,1,1,1,1,1,1}
};//迷宫地图,0表示路,1表示墙,2表示入口,3表示出口
int enterx,entery;//表示迷宫起点
int exitx,exity;//表示迷宫终点
//栈的操作
void init(Linkstack *s)//初始化栈
{
if(!s)
{
return ;
}
s->top=NULL;
s->cnt=0;
}
void push(Linkstack *s,stacknode *p)//入栈操作
{
p->next=s->top;
s->top=p;
s->cnt++;
}
int if_stack_empty(Linkstack *s)//判断栈是否为空
{
if(s->cnt!=0)
{
return 0;
}
else
{
return 1;
}
}
stacknode *pop(Linkstack *s)//出栈
{
stacknode *p;
p=s->top;
s->top=p->next;
s->cnt--;
return p;
}
stacknode *peek(Linkstack *s)//取栈顶
{
stacknode *p;
p=s->top;
return p;
}
//迷宫操作
void print_map()//打印地图
{
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
printf("%d ",mapp[i][j]);
}
printf("\n");
}
printf("\n");
}
void find_enter()//寻找入口和出口
{
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
if(mapp[i][j]==2)
{
enterx=i;
entery=j;
}
if(mapp[i][j]==3)
{
exitx=i;
exity=j;
}
}
}
}
void Mark(stacknode *q)//标记走过的路径
{
mapp[q->x][q->y]=2;
//print_map();
}
int PathStack(Linkstack *s)//寻找路径
{
stacknode *p;
p=(linkstack)malloc(sizeof(stacknode));
p->x=enterx;
p->y=entery;
p->dir=0;
push(s,p);
int f=0;
while(!if_stack_empty(s))
{
stacknode *q;
q=peek(s);
int x=q->x;
int y=q->y;
int dir=q->dir;
Mark(q);
if(x==exitx&&y==exity)
{
return 1;
}
switch(dir)
{
case Up:
if(x-1>=0&&mapp[x-1][y]==0||mapp[x-1][y]==3)
{
stacknode *up=(linkstack)malloc(sizeof(stacknode));
up->x=x-1;
up->y=y;
up->dir=0;
push(s,up);
}
q->dir++;
continue;
case Right:
if(y+1<col&&mapp[x][y+1]==0||mapp[x][y+1]==3)
{
stacknode *right=(linkstack)malloc(sizeof(stacknode));
right->y=y+1;
right->x=x;
right->dir=0;
push(s,right);
}
q->dir++;
continue;
case Down:
if(x+1<row&&mapp[x+1][y]==0||mapp[x+1][y]==3)
{
stacknode *down=(linkstack)malloc(sizeof(stacknode));
down->y=y;
down->x=x+1;
down->dir=0;
push(s,down);
}
q->dir++;
continue;
case Left:
if(y-1>=0&&mapp[x][y-1]==0||mapp[x][y-1]==3)
{
stacknode *left=(linkstack)malloc(sizeof(stacknode));
left->y=y-1;
left->x=x;
left->dir=0;
push(s,left);
}
q->dir++;
continue;
}
p=pop(s);
mapp[p->x][p->y]=0;
}
return 0;
}
int main()
{
find_enter();
Linkstack s;
init(&s);
print_map();
//printf("%d %d %d %d",enterx,entery,exitx,exity);
if(PathStack(&s)==1)
{
printf("找到路径!\n");
print_map();
}
else
{
printf("没有找到路径!\n");
}
return 0;
}