运用广度优先算法,利用链式队列处理迷宫问题(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; //记录方向(不重要)
struct node *next;
struct node *pre; //记录父节点
};
typedef struct queue{
node *rear,*front;
};
//入队列
bool push(queue *que,node *q,int x,int y){
node *p=(node *)malloc(sizeof(node));
p->x=x;
p->y=y;
p->z=-1;
p->pre=q;
maze[x][y]=-1;
que->rear->next=p;
que->rear=p;
que->rear->next=null;
return true;
}
bool path(int xi,int xj,int yi,int yj){
//队列初始化
queue *que=(queue *)malloc(sizeof(queue));
que->rear=(node *)malloc(sizeof(node));
que->rear->next=null;
que->front=que->rear; //对头不放数据
//开始走迷宫(入栈)
node *p,*q=que->front;
push(que,q,xi,xj);
while(que->front!=que->rear){
maze[yi][yj]=0; //出口始终保持为零(可走),考虑到多条路径的情况,让出口的坐标可以无限次数入队列
q=q->next;
int i,j,k;
i=q->x;
j=q->y;
k=-1;
int x=i,y=j;
if(q->x==yi && q->y==yj){ //走到出口
k=4; //出口不作父节点 ,不参与下面的while循环
//出口周围的点全部走过,代表所有路径已经找完、退出循环
if(maze[yi][yj+1]!=0 && maze[yi][yj-1]!=0 && maze[yi+1][yj]!=0 && maze[yi-1][yj]!=0 ){
break;
}
}
while(k<=3){ //将可走的路都入队列
k++;
if(k==0){
x=i;
y=j+1;
if(maze[x][y]==0) push(que,q,x,y); //左
}else if(k==1){
x=i+1;
y=j;
if(maze[x][y]==0) push(que,q,x,y); //下
}else if(k==2){
x=i;
y=j-1;
if(maze[x][y]==0) push(que,q,x,y); //右
}else{
x=i-1;
y=j;
if(maze[x][y]==0) push(que,q,x,y); //上
}
}
q->z=k;
}
//打印路径
int count=0; //记录路径条数
p=que->front->next;
while(p!=que->rear){
if(p->x==yi && p->y==yj){ //每找到一次出口坐标,打印其对应的路径
count++;
printf("路径%d(倒序):\n",count);
q=p;
while(q!=que->front){
printf("(%d,%d) ",q->x,q->y);
q=q->pre; //通过找父节点倒序打印路径
}
printf("\n");
}
p=p->next;
}
if(count>0){ //没有路径、释放队列空间
free(que);
return true;
}
free(que);
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;
}
运行结果: