迷宫问题

作者在 2010-05-13 22:02:23 发布以下内容
#include<stdio.h>
#define M 6
#define N 6
int maze[M][N]={1,2,1,1,1,1, 1,0,1,0,0,1, 1,0,0,0,0,1, 1,1,0,0,1,1, 1,0,1,0,0,1, 1,1,1,1,3,1};
typedef struct list
{
  int m,n;
  struct list*next;
  struct list*back;        
}node,*pointer;
int pass[M][N];
int m,n;
pointer ptr,preptr,first,p;
 
void Start()
{ int i,j;
  for(i=0;i<M-1;i++)
  {
    for(j=0;j<N-1;j++)
       if(maze[i][j]==2 )break;
                      
  }     
  m=i;n=j;
  ptr=(pointer)malloc(sizeof(node));
  ptr->m=m;ptr->n=n;
  ptr->next=NULL;ptr->back=NULL;
  first=ptr;
}



void Search()
{
  while((maze[m][n]!=3)&&(ptr->back!=NULL))
    {
       if(maze[m+1][n]==1||pass[m+1][n])
         if(maze[m][n+1]==1||pass[m][n+1])
           if(maze[m][n-1]==1||pass[m][n-1])
             if(maze[m-1][n]==1||pass[m-1][n])
               {
                 if(ptr->back!=NULL)
                   {
                     ptr=ptr->back;free(ptr->next);ptr->next=NULL;                 
                   }                               
                 m=ptr->m; n=ptr->n;  
               }                    
             else
             {
               m-=1;
               ptr->next=(pointer)malloc(sizeof(node));
               ptr->next->m=m;ptr->next->n=n;
               preptr=ptr;ptr->next->next=NULL;
               pass[m][n]=1; ptr=ptr->next;ptr->back=preptr;  
             }                     
           else
           {
             n-=1;
               ptr->next=(pointer)malloc(sizeof(node));
               ptr->next->m=m;ptr->next->n=n;
               preptr=ptr;ptr->next->next=NULL;
               pass[m][n]=1; ptr=ptr->next;ptr->back=preptr;     
           }
         else
         {
           n+=1;
            ptr->next=(pointer)malloc(sizeof(node));
            ptr->next->m=m;ptr->next->n=n;
            preptr=ptr;ptr->next->next=NULL;
            pass[m][n]=1;ptr=ptr->next;ptr->back=preptr;   
         }    
       else
        {
        m+=1;
         ptr->next=(pointer)malloc(sizeof(node));
         ptr->next->m=m;ptr->next->n=n;
         preptr=ptr;ptr->next->next=NULL;
         pass[m][n]=1;ptr=ptr->next;ptr->back=preptr;      
        }
    }
        if(ptr->back==NULL)
         printf("%s\n","找不到出口,无出口");
        if(maze[m][n]==3)
        printf("找到出口--%d,%d\n",m,n);
        pointer p=first;
        while(p)
        {
          printf("%d,%d\n",p->m,p->n);
          p=p->next;        
        }
    }    

int main()
{ int i,j;
   for(i=0;i<M;i++)
    { for(j=0;j<N;j++)
      printf(" %d",maze[i][j]);
      printf("\n");}
      
Start(maze);
Search(maze);
getch();
return 0;  
 
}
 

默认分类 | 阅读 495 次
文章评论,共0条
游客请输入验证码
浏览10941次
文章分类
最新评论