我们用一个二维数组表示迷宫的点,1能走,0不能走,用回溯法写,用一个简单一点的迷宫做事例:
#define _CRT_SECURE_NO_WARNINGS 1
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#define N 6
#define length N * N
typedef struct Pos
{
int x;//横坐标0到N-1
int y;//纵坐标0到N-1
}Pos;
typedef struct Stack
{
Pos* _top;
Pos* _end; //栈顶指针
int stackSize;
}Stack;
void pathPrint();
void MazeGetShortPath(Pos entry, Stack* path);
void myStackInit(Stack* s);
void zoulu(Pos now, int* arr);
void myStackPush(Stack* s, Pos x);
Pos myStackPop(Stack* s);
Stack shortPath;
Stack* s = &shortPath;
Pos enterPoint;
Pos finalPoint;
int count = 0;
int main()
{
int maze[N][N] =
{
{ 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 1, 0 },
{ 0, 0, 1, 0, 1, 0 },
{ 0, 0, 1, 1, 1, 0 },
{ 0, 0, 1, 0, 1, 1 },
{ 0, 0, 1, 0, 0, 0 },
};
enterPoint.x = 5;
enterPoint.y = 2;
finalPoint.x = 4;
finalPoint.y = 5;
myStackInit(s);
MazeGetShortPath(enterPoint, s, &maze);
system("pause");
return 0;
}
void pathPrint()
{
int x = 0;
int y = 0;
int i = 0;
Pos* tmp = s->_end;
while (s->_top != s->_end)
{
i++;
x = s->_end->x;
y = s->_end->y;
s->_end++;
printf("%d、(%d,%d)\n", i, x, y);
}
s->_end = tmp;
}
void zoulu(Pos now, int arr[N][N])
{
if (finalPoint.x == now.x && finalPoint.y == now.y)
{
count++;
printf("--------第%d种走法--------\n",count);
pathPrint();
Pos p = myStackPop(s);
arr[p.x][p.y] = 1;
return;
}
if (1 == arr[now.x - 1][now.y] && now.x - 1 >= 0)
{
Pos nowup;
nowup.x = now.x - 1;
nowup.y = now.y;
myStackPush(s, nowup);
arr[now.x - 1][now.y] = -1;//标记走过
zoulu(nowup, arr);
}
if (1 == arr[now.x + 1][now.y] && now.x + 1 < N)
{
Pos nowdn;
nowdn.x = now.x + 1;
nowdn.y = now.y;
myStackPush(s, nowdn);
arr[now.x + 1][now.y] = -1;//标记走过
zoulu(nowdn, arr);
}
if (1 == arr[now.x][now.y - 1] && now.y - 1 >= 0)
{
Pos nowlf;
nowlf.x = now.x;
nowlf.y = now.y - 1;
myStackPush(s, nowlf);
arr[now.x][now.y - 1] = -1;//标记走过
zoulu(nowlf, arr);
}
if (1 == arr[now.x][now.y + 1] && now.y + 1 < N)
{
Pos nowrg;
nowrg.x = now.x;
nowrg.y = now.y + 1;
myStackPush(s, nowrg);
arr[now.x][now.y + 1] = -1;//标记走过
zoulu(nowrg, arr);
}
Pos p = myStackPop(s);
arr[p.x][p.y] = 1;
}
void MazeGetShortPath(Pos entry, Stack* path, int arr[N][N])
{
myStackPush(path, entry);
zoulu(*(s->_top - 1), arr);
}
void myStackInit(Stack* s)
{
//给栈申请空间
s->_end = (Pos*)malloc(length * sizeof(Pos));
//判断是否申请成功
if (!s->_end)
{
exit(0);
}
//初始化栈数组空间
s->_top = s->_end;//最开始栈顶等于栈低
s->stackSize = length;
return;
}
void myStackPush(Stack* s, Pos x)
{
//断言
assert(s);
if (s->stackSize == s->_top - s->_end)
{
printf("空间已满,追加空间");
s->_end = (Pos*)realloc(s->_end, (s->stackSize + length) * sizeof(Pos));
if (!s->_end)
{
exit(0);
}
s->_top = s->_end + s->stackSize;//设置栈顶
s->stackSize += length;//设置栈长度
}
*(s->_top) = x;//设置x
s->_top++;
return;
}
Pos myStackPop(Stack* s)
{
assert(s);
if (StackEmpty(s))
{
printf("栈为空");
return;
}
return *--(s->_top);
}
结果为: