修改后的迷宫求解问题

上次那种迷宫求解不是最优的解:经过改进后终于找到最优解:请看下面的代码:
#include "stdio.h"
struct {
        int i;
        int j;
        int di;/*下一个可以走的方位*/
}st[50];

int miGong(int x,int y,int xe,int ye){
     int i,j,k,di,find;  /*find 用于标记是否有下一条路,di是下一个可走的方位号码,k用于循环输出结果*/
     int a[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 top=-1;
     find=0;/*表示还没找到可走相邻方块*/
     top++;
     st[top].i=x;st[top].j=y;
     st[top].di=-1;a[1][1]=-1;
     while(top>-1){
         i=st[top].i;j=st[top].j;di=st[top].di; /*取栈顶元素*/
         if(i==xe && j==ye){
             printf("the migong list:/n");
             for(k=0;k<=top;k++){
                 printf("(%d,%d)/t",st[k].i,st[k].j);
                 if((k+1)%5==0){
                     printf("/n");
                 }
             }
             printf("/n");
             return 1;
         }
         find=0;
         while(di<4 && find==0){
             di++;
             switch(di){
                 case 0:i=st[top].i+1;j=st[top].j;break;
                 case 1:i=st[top].i;j=st[top].j+1;break;
                 case 2:i=st[top].i-1;j=st[top].j;break;
                 case 3:i=st[top].i;j=st[top].j-1;break;

             }
             if(a[i][j]==0){
                 find=1;
             }
         }
         if(find==1){
             st[top].di=di;
             top++;
             st[top].i=i;
             st[top].j=j;
             st[top].di=-1;
             printf("i=%d,j=%d/n",st[1].i,st[1].j);
             a[i][j]=-1;

         }else{
             /*a[st[top].i][st[top].j]=0;*/
             top--;
         }
     }
     return 0;
}
main(){
   miGong(1,1,8,8);
   getch();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值