迷宫问题直接dfs或者bfs多easy,非要用自己搞的链栈。。。。
不过思想很类似搜索
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
typedef int Status;
struct node{
int x;
int y;
};
typedef struct snode{
node pos;
struct snode* next;
}snode;
typedef struct linkstack{
snode* top;
snode* bottom;
int length;
}linkstack;
Status creat(linkstack* S){//创建一个空栈
S->top=S->bottom=(snode*)malloc(sizeof(snode));
if(!S->top){
printf("申请空间失败!\n");
return ERROR;
}
S->top->next=NULL;
S->bottom->next=NULL;
S->length=0;
return OK;
}
bool empty(linkstack S){//判断栈是否为空
return !S.length;
}
int size(linkstack S){//返回栈的大小
return S.length;
}
Status push(linkstack* S,node pos){//元素入栈
snode* newx=(snode*)malloc(sizeof(snode));
if(!newx){
printf("申请空间失败!\n");
return ERROR;
}
newx->pos=pos;
newx->next=S->top->next;
S->top->next=newx;
if(!S->length)
S->bottom=S->bottom->next;
S->length++;
return OK;
}
Status pop(linkstack* S){//弹出栈顶元素
if(!S->length){
printf("当前栈已经为空!\n");
return ERROR;
}
snode* del=S->top->next;
S->top->next=del->next;
free(del);
S->length--;
return OK;
}
Status gettop(linkstack S,node& pos){//获得栈顶元素 存到pos中
if(!S.length){
printf("当前栈为空!\n");
return ERROR;
}
pos=S.top->next->pos;
return OK;
}
Status show(linkstack S){//输出当前栈的内容
if(!S.length){
printf("空!\n");
return ERROR;
}
snode* p=S.top->next;
while(p){
printf("(%d,%d)\n",p->pos.x,p->pos.y);
p=p->next;
}
printf("\n");
return OK;
}
Status destroy(linkstack* S){//销毁当前栈
snode* del;
while(S->top){
del=S->top;
S->top=S->top->next;
free(del);
}
S->top=S->bottom=NULL;
return OK;
}
int main()
{
int mp[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
};
int sx=1,sy=1,ex=8,ey=8;
node now;
now.x=sx;
now.y=sy;
mp[sx][sy]=-1;//走过了
linkstack s;
creat(&s);
push(&s,now);
while(!empty(s)){
gettop(s,now);
if(now.x==ex&&now.y==ey)
break;//终点
if(!mp[now.x][now.y+1]){//右
node next=now;
next.y=now.y+1;
mp[next.x][next.y]=-1;
push(&s,next);
continue;
}
if(!mp[now.x+1][now.y]){//下
node next=now;
next.x=now.x+1;
mp[next.x][next.y]=-1;
push(&s,next);
continue;
}
if(!mp[now.x][now.y-1]){//左
node next=now;
next.y=now.y-1;
mp[next.x][next.y]=-1;
push(&s,next);
continue;
}
if(!mp[now.x-1][now.y]){//上
node next=now;
next.x=now.x-1;
mp[next.x][next.y]=-1;
push(&s,next);
continue;
}
pop(&s);
}
linkstack path;
creat(&path);
node step;
while(!empty(s)){
gettop(s,step);
push(&path,step);
pop(&s);
}//换成正向
printf("走出迷宫的路径为:\n");
show(path);
destroy(&s);
destroy(&path);
return 0;
}