问题描述:
编写一个程序exp3-5.cpp,输出下图迷宫中的最短路径。
算法分析:
采用队列,利用其先进先出的特性,每次队列元素出完时每条路径长度仅增加1,说简单点就是,每次各个方块只往后走一格,看谁最先到出口,则该路径就是最短路径。
代码展示:
#include "pch.h"
#include <iostream>
using namespace std;
typedef struct //定义方块,i、j分别为该方块的横纵坐标,di为下一个方块的的索引值
{
int i;
int j;
int di;
}Box;
typedef Box ElemType;
typedef struct
{
ElemType data[16];
int top;
int sai;
}StType;
void InitStack(StType *&s) {
s = (StType*)malloc(sizeof(StType));
s->top = -1;
}
void DestroyStack(StType *&s) {
free(s);
}
bool StackEmpty(StType *s) {
return (s->top == -1);
}
bool Push(StType *&s, ElemType e) {
if (s->top == 15)
return false;
s->top++;
s->data[s->top] = e;
return true;
}
bool Pop(StType *&s, ElemType &e) {
if (s->top == -1)
return false;
e = s->data[s->sai];
s->sai--;
return true;
}
bool mgpath(int xi, int yi, int xe, int ye,int mg[][6]);
void print(StType *st);
int main()
{
int mg[][6] = { //定义迷宫地图
{1,1,1,1,1,1},
{1,0,0,0,1,1},
{1,0,1,0,0,1},
{1,0,0,0,1,1},
{1,1,0,0,0,1},
{1,1,1,1,1,1}
};
bool b = mgpath(1, 1, 4, 4, mg);
return 0;
}
bool mgpath(int xi, int yi, int xe, int ye,int mg[][6]) //求最短路径
{
Box e;
int i, j, di, i1, j1,a=0,b=0;
StType *st;
InitStack(st);
e.i = xi;e.j = yi;e.di = -1;
Push(st, e);
b++;
mg[xi][yi] = -1;
while (!StackEmpty(st)) {
st->sai = st->top;
a = b;
b = 0;
for (int n = 0;n < a;n++)
{
Pop(st, e);
i = e.i;j = e.j;
if (i == xe && j == ye) { //若找到最短路径,则调用print方法输出路径。
print(st);
DestroyStack(st);
return true;
}
for (di = 0;di < 4;di++) {
switch (di)
{
case 0:i1 = i - 1;j1 = j;break;
case 1:i1 = i;j1 = j + 1;break;
case 2:i1 = i + 1;j1 = j;break;
case 3:i1 = i;j1 = j - 1;break;
}
if (mg[i1][j1] == 0) {
e.i = i1;e.j = j1;
e.di = st->sai+1;
Push(st, e);
mg[i1][j1] = -1;
b++;
}
}
}
}
DestroyStack(st);
return false;
}
void print(StType *st)
{
int k = st->top, j, ns = 0;
cout << endl;
do {
j = k;
k = st->data[k].di;
st->data[j].di = -1;
} while (k!=0);
cout << "一条迷宫路径如下:" << endl;
k = 0;
while (k < 16) {
if (st->data[k].di == -1) {
ns++;
printf("\t(%d,%d)",st->data[k].i,st->data[k].j);
if (ns % 5 == 0) cout << endl;
}
k++;
}
cout << endl;
}
运行结果: