问题描述
给定一个M*N的迷宫,求一条从指定入口到出口的迷宫路径。用栈采用顺序栈存储结构。代码如下
数据结构
用队列解决求迷宫路径问题。使用一个顺序队qu保存走过的方块。这里使用顺序队列而不是环形队列屎因为在找到出口时需要利用队列中的所有方块查找一条迷宫路径。
运算算法
首先将入口(xi,yi),进队,在队列不空时循环出队一个方块e.然后查找方块e的所有相邻可走方块。当找到出口时,通过出口方块的pre值前推找到出口,所有经过的中间方块构成一条迷宫路径。利用的是广度优先搜索方法。为了正确输出路径,在前面的回推过程中修改路径上的每一个pre值,使该迷宫路径上的所有方块的pre值置为-1,然后从开头输出pre为-1的方块,从而正向输出了一条迷宫路径。
代码实现
#include<stdio.h>
#include<malloc.h>
#define MaxSize 50
#define M 8
#define N 8
typedef struct
{
int i,j;
int pre;
}Box;
typedef struct
{
Box data[MaxSize];
int front,rear;
}QuType;
void InitQueue(QuType*&q)
{
q = (QuType*)malloc(sizeof(QuType));
q->front = q->rear = -1;
}
void DestroyQueue(QuType*&q)
{
free(q);
}
bool QueueEmpty(QuType*q)
{
return(q->front == q->rear);
}
bool enQueue(QuType*&q, Box e)
{
if (q->rear == MaxSize - 1)
return false;
q->rear++;
q->data[q->rear] = e;
return true;
}
bool deQueue(QuType*&q, Box&e)
{
if (q->front == q->rear)
return false;
q->front++;
e = q->data[q->front];
return true;
}
int mg[M+2][N+2] = { {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} };
void print(QuType *qu, int front)
{
int k = front, j, ns = 0;
printf("\n");
do
{
j = k;
k = qu->data[k].pre;
qu->data[j].pre = -1;
} while (k != 0);
printf("一条迷宫路径如下:\n");
k = 0;
while (k < MaxSize)
{
if (qu->data[k].pre == -1)
{
ns++;
printf("\t(%d,%d)", qu->data[k].i, qu->data[k].j);
if (ns % 5 == 0)
printf("\n");
}
k++;
}
printf("\n");
}
bool mgpath1(int xi, int yi, int xe, int ye)
{
Box e;
int i, j, di, il, jl;
QuType*qu;
InitQueue(qu);
e.i = xi;e.j = yi;e.pre = -1;
enQueue(qu, e);
mg[xi][yi] = -1;
while (!QueueEmpty(qu))
{
deQueue(qu, e);
i = e.i; j = e.j;
if (i == xe && j == ye)
{
print( qu, qu->front);
DestroyQueue(qu);
return true;
}
for (di = 0;di < 4;di++)
{
switch (di)
{
case 0:
il = i - 1; jl = j; break;
case 1:
il = i; jl = j + 1; break;
case 2:
il = i + 1; jl = j; break;
case 3:
il = i; jl = j - 1; break;
}
if (mg[il][jl] == 0)
{
e.i = il; e.j = jl;
e.pre = qu->front;
enQueue(qu, e);
mg[il][jl] = -1;
}
}
}
DestroyQueue(qu);
return false;
}
int main()
{
if (! mgpath1(1, 1, M, N))
printf("没有解");
return 1;
}
结果