C语言数据结构----栈实现迷宫
https://blog.csdn.net/qq_43079376/article/details/89337578
#include <stdio.h>
#define MAX 30
typedef struct
{
int x;
int y;
int di;
}Box;
typedef struct
{
int top;
Box data[MAX];
}Stack;
int map[10][10]={
{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}
};
int search(int beginX,int beginY,int endX,int endY)
{
int i,j,k,di,find;
Stack s;
s.top = -1;
s.top++;
s.data[s.top].x = beginX;
s.data[s.top].y = beginY;
s.data[s.top].di = -1;
map[beginX][beginY]=-1;
while (s.top>-1)
{
i = s.data[s.top].x;
j = s.data[s.top].y;
di = s.data[s.top].di;
//结束,输出结果
if (i == endX&&j == endY)
{
printf("迷宫路径如下:\n");
for (k = 0; k < s.top; ++k) {
if ((k+1)%5!=0)
{
printf("(%d,%d)\t",s.data[k].x,s.data[k].y);
} else {
printf("\n");
}
}
return 1;
}
find = 0;
while (di<4&&find==0)
{
di++;
switch (di)
{
//西
case 0:
i = s.data[s.top].x-1;
j = s.data[s.top].y;
break;
//南
case 1:
i = s.data[s.top].x;
j = s.data[s.top].y+1;
break;
//东
case 2:
i = s.data[s.top].x+1;
j = s.data[s.top].y;
break;
//北
case 3:
i = s.data[s.top].x;
j = s.data[s.top].y-1;
break;
}
if (map[i][j] == 0)
{
find = 1;
}
}
if (find == 1)
{
s.data[s.top].di = di;
s.top++;
s.data[s.top].x = i;
s.data[s.top].y = j;
s.data[s.top].di = -1;
map[i][j] = -1;
} else {
map[s.data[s.top].x][s.data[s.top].y] = 0;
s.top --;
}
}
return 0;
}
int main()
{
if(!search(1,1,8,8))
{
printf("NO");
}
return 0;
}
以上就是源码部分,接下来我将一步一步解读里面的每一个步骤:
栈的结构设计如下:
typedef struct
{
int x; //二维数组的行
int y; //二维数组的列
int di;//假如退栈时记录了上次在该点走过的方向
}Box;
typedef struct
{
Box data[MAX];//存储走过的路径的行列
int top;//记录栈顶,后期回溯方便弹出
}
地图(二维数组):
int map[10][10]={
{
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},
{