迷宫算法

Here is a simple implementation for maze issue.

#include  < stdio.h >
#include 
< stdlib.h >
#include 
< stdext.h >
#include 
< stdbool.h >
#define  ROW_NUM 8
#define  COL_NUM 8

typedef 
struct  {
    
int  x;
    
int  y;
    
struct  position *  next;
} position;

static   int  maze[ROW_NUM][COL_NUM]  =  {{ 0 , 0 , 1 , 0 , 0 , 0 , 0 , 1 }, 
                                 {
1 , 1 , 0 , 1 , 1 , 0 , 1 , 0 }, 
                                 {
0 , 1 , 0 , 1 , 1 , 0 , 1 , 0 }, 
                                 {
0 , 1 , 0 , 1 , 0 , 1 , 0 , 1 }, 
                                 {
0 , 1 , 1 , 0 , 1 , 1 , 1 , 1 }, 
                                 {
0 , 0 , 0 , 1 , 1 , 0 , 0 , 1 }, 
                                 {
1 , 1 , 0 , 1 , 0 , 1 , 1 , 0 }, 
                     {
0 , 0 , 1 , 0 , 1 , 1 , 0 , 0 }};

bool  isvalid( int  x,  int  y)
{
    
if (x  >=   0   &&  x  <  ROW_NUM  &&  y  >=   0   &&  y  <  COL_NUM  &&  maze[x][y]  ==   0 return   true ;
    
return   false ;
}

bool  inpath( int  x,  int  y, position *  pos)
{
    
while (pos  !=  NULL) {
        
if (pos -> ==  x  &&  pos -> ==  y)  return   true ;
        pos 
=  (position * )(pos -> next);
    }
    
return   false ;
}


static   bool  pathfound  =   false ;

void  walkmaze( int  x,  int  y, position *  pos)
{
    
if (pathfound  ||   ! isvalid(x, y)  ||  inpath(x, y, pos))  return ;
    
if (x  ==  ROW_NUM - 1   &&  y  ==  COL_NUM - 1 ) {
        printf(
" (%d,%d) " , x, y);
        
while (pos  !=  NULL) {
            printf(
"  <- (%d,%d) " , pos -> x, pos -> y);
            pos 
=  (position * )pos -> next;
        }
        puts(
"" ); pathfound  =   true return ;
    }
    position pos6; pos6.x 
=  x, pos6.y  =  y; pos6.next  =  pos; walkmaze(x + 1 , y + 1 & pos6);
    position pos8; pos8.x 
=  x, pos8.y  =  y; pos8.next  =  pos; walkmaze(x  , y + 1 & pos8);
    position pos5; pos5.x 
=  x, pos5.y  =  y; pos5.next  =  pos; walkmaze(x + 1 , y  ,  & pos5);
    position pos1; pos1.x 
=  x, pos1.y  =  y; pos1.next  =  pos; walkmaze(x - 1 , y + 1 & pos1);
    position pos2; pos2.x 
=  x, pos2.y  =  y; pos2.next  =  pos; walkmaze(x - 1 , y  ,  & pos2);
    position pos4; pos4.x 
=  x, pos4.y  =  y; pos4.next  =  pos; walkmaze(x + 1 , y - 1 & pos4);
    position pos7; pos7.x 
=  x, pos7.y  =  y; pos7.next  =  pos; walkmaze(x  , y - 1 & pos7);
    position pos3; pos3.x 
=  x, pos3.y  =  y; pos3.next  =  pos; walkmaze(x - 1 , y - 1 & pos3);
}

int  main()
{
    walkmaze(
0 0 , NULL);
    
return   0 ;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值