C语言实现迷宫问题](深度优先搜索)

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值