走迷宫 回溯法

来源:互联网 发布:软件行业净利润率 编辑:程序博客网 时间:2024/06/10 04:06

#include <iostream>
#include <windows.h>
using namespace std;
#define FINISH_X 4
#define FINISH_Y 11
#define M 1000
char a[12][12] = {{'#','#','#','#','#','#','#','#','#','#','#','#'},
                  {'#',' ',' ',' ','#',' ',' ',' ',' ',' ',' ','#'},
                  {'+',' ','#',' ','#',' ','#','#','#','#',' ','#'},
                  {'#','#','#',' ','#',' ',' ',' ',' ','#',' ','#'},
                  {'#',' ',' ',' ',' ','#','#','#',' ','#',' ',' '},
                  {'#','#','#','#',' ','#',' ','#',' ','#',' ','#'},
                  {'#',' ',' ','#',' ','#',' ','#',' ','#',' ','#'},
                  {'#','#',' ','#',' ','#',' ','#',' ','#',' ','#'},
                  {'#',' ',' ',' ',' ',' ',' ',' ',' ','#',' ','#'},
                  {'#','#','#','#','#','#',' ','#','#','#',' ','#'},
                  {'#',' ',' ',' ',' ',' ',' ','#',' ',' ',' ','#'},
                  {'#','#','#','#','#','#','#','#','#','#','#','#'},
};
int horizotal[4]={-1,1,0,0};
int vertical[4] = {0,0,-1,1};

void display()
{
     system("cls");
     int i,j;
     for(i=0;i<12;i++)
     {
      for(j=0;j<12;j++)
       cout << a[i][j] << ' ';
       cout << endl;
     }    
}
void backtrack(int x,int y)
{
     if(x==FINISH_X&&y==FINISH_Y)
     {
      cout << "Success " << endl;
      system("pause"); 
      exit(0) ;
     }
     else
     {
        int i;
        a[x][y] = '+';
        display();
        Sleep(M);
        for(i=0;i<4;i++)
        {
           if(a[x+vertical[i]][y+horizotal[i]]==' ')
           backtrack(x+vertical[i],y+horizotal[i]);            
        }//for
         a[x][y] = ' ';
         display();
         Sleep(M);
     }//else   
    
}
int main()
{
   backtrack(2,0);
   system("pause");
   return 0;   
}

原创粉丝点击