运用深度优先算法,利用链式堆栈处理迷宫问题(C语言)
程序代码:
#include<stdio.h>
#include<stdlib.h>
#define null 0
int maze[10][10]= //创建迷宫(0可走,1不可走,-1已走过)
{{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}};
typedef struct node{
int x;
int y;
int z; //记录方向(1左,2下,3右,0上)
struct node *next;
};
typedef struct stack{
node *top;
};
bool push(stack *s,node *q){
q->next=s->top;
s->top=q;
return true;
}
bool pop(stack *s,node *q){
if(s->top=null) return false;
s->top=q->next;
free(q);
return true;
}
bool path(int xi,int xj,int yi,int yj){
//初始化栈
stack *s=(stack *)malloc(sizeof(stack));
s->top=null;
//入口进栈
node *q=(node *)malloc(sizeof(node));
node *r;
q->x=xi;
q->y=xj;
q->z=-1;
push(s,q);
maze[xi][xj]=-1; //走过的位置记为-1
//走迷宫
while(s->top){
q=s->top;
if(q->x==8 && q->y==8){ //走到出口打印路径
printf("路径1(倒序):\n");
while(q){
printf("(%d,%d) ",q->x,q->y);
r=q;
q=q->next;
free(r);
}
printf("\n");
s->top=null;
free(s); //输出路径之后、释放栈空间
return true;
}
//找路径、入栈
int i,j,k;
i=q->x;
j=q->y;
k=-1;
int x=1,y=j;
while(k<=3){
k++;
if(k==0){ //向左
x=i;
y=j+1;
}else if(k==1){ //向下
x=i+1;
y=j;
}else if(k==2){ //向右
x=i;
y=j-1;
}else{ //向上
x=i-1;
y=j;
}
if(maze[x][y]==0) break;
}
if(maze[x][y]==0){ //有路可走、入栈
q->z=k;
node *p=(node *)malloc(sizeof(node));
p->x=x;
p->y=y;
p->z=-1;
push(s,p);
maze[x][y]=-1;
}else{ //无路可走、出栈
pop(s,q);
}
}
free(s); //没有路径、退出循环、释放栈空间
return false;
}
//打印迷宫
int print(int maze[][10]){
printf("迷宫:\n");
int i,j;
for(i=0;i<10;i++){
for(j=0;j<10;j++) {
printf("%2d",maze[i][j]);
}
printf("\n");
}
printf("\n");
}
int main(){
print(maze);
if(path(1,1,8,8)) printf("此迷宫有解!\n \n");
else printf("此迷宫无解!\n \n");
print(maze);
return 0;
}
运行结果: