C语言实现迷宫问题](这里写自定义目录标题)
C语言实现迷宫问题](深度优先搜索)
小白一枚,C语言实现迷宫问题,思路为,先将初始点(i,j, di)入栈,进入循环,先出栈,之后判断临近点(row,col),如果这个点可行,留下标记(在0,1迷宫中用2来标记走过的路,然后将i,j,di入栈),然后更新点坐标,找到为止,代码如下(勿喷,嘻嘻)
#include<stdio.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 1000
typedef struct { //栈中的结构体
int x;
int y;
int di;
}Box;
typedef struct { //栈
Box* base;
Box* top;
int stacksize;
}Sqstack;
void MazePath(int a[][10], Box start, Box end,Sqstack *S);
void Move( int i, int j, int di,int *row,int * col);
int Initstack(Sqstack* S) { //栈的初始化
S->base = (Box*)malloc(sizeof(Box) * STACK_INIT_SIZE);
if (!S->base) return 0;
S->top = S->base;
S->stacksize = STACK_INIT_SIZE;
return 1;
}
void Push(Sqstack* S, Box e) { //入栈
if (S->top - S->base == S->stacksize) {
printf("栈满");
return;
}
else {
*S->top = e;
S->top++;
}
}
void Pop(Sqstack* S,Box *e) { //出栈
if (S->top == S->base) {
printf("栈空");
}
else {
*e = *--S->top;
}
}
void Move(int i, int j, int di, int* row, int* col) {
if (di == 0) {
*row = i + 1;
*col = j;
}
if (di == 1) {
*col = j+1;
*row = i;
}
if (di == 2) {
*row = i-1;
*col = j;
}
if (di == 3)
{
*col = j - 1;
*row = i;
}
}
void MazePath(int a[][10], Box start, Box end,Sqstack *S) {
int i, j; //当前位置
int row, col; //下一个可能出现的位置
int di; //方向
int flag = 0, flag1 = 0;
Box cornow; //出入栈时用的元素
Box nextcornow;
i = 1;
j = 1;
di = 0;
a[i][j] = 2;
cornow.x = 1;
cornow.y = 1;
cornow.di = 0; //迷宫初始位置和方向
Push(S, cornow);
do {
Pop(S,&cornow);
i = cornow.x;
j = cornow.y;
di = cornow.di;
while (di < 4) {
Move(i, j, di, &row, &col);
if (a[row][col] == 0) {
cornow.x = i;
cornow.y = j;
cornow.di = di;
a[row][col] = 2;
Push(S, cornow);
i = row;
j = col;
di = -1;
}
di++;
}
if (i == end.x && j == end.y) {
printf("已找到end \n");
flag1 = 1;
break;
}
}while(S->top >= S->base);
}
int main()
{
Sqstack S;
int a[][10] = { {1,1,1,1,1,1,1,1,1,1},
{1,0,1,1,0,0,0,0,0,0},
{1,0,1,1,1,1,1,1,1,1},
{1,0,0,0,0,0,1,1,1,1},
{1,1,1,1,1,0,0,1,1,1},
{1,1,1,1,1,1,0,0,0,1},
{1,1,0,0,0,0,0,0,1,1},
{1,1,0,1,1,1,1,1,0,1},
{1,0,0,0,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,0,0} };
Box start,end;
int i,j;
int flag;
flag = Initstack(&S);
if (flag == 0) exit(1);
start.x = 1;
start.y = 1;
start.di = 0;
end.x = 8;
end.y = 8;
end.di = 0;
MazePath(a, start, end,&S);
printf("迷宫现在情况为\n");
for (i = 0;i < 10; i++){
for(j = 0;j < 10; j++){
printf("%4d",a[i][j]);
}
printf("\n");
}
printf("行走的路径为\n");
do{
printf("(%d,%d,%d)\n",S.base->x,S.base->y,S.base->di);
S.base++;
}while(S.base <= S.top);
return 0;
}