迷宫问题

来源:互联网 发布:怎样查找com端口号 编辑:程序博客网 时间:2024/05/02 00:11

#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; 
 
}