骑士周游 回溯法

#include <iostream>
#define N 5

using namespace std;

int chess[N][N];
int horizontal[8]={2,1,-1,-2,-2,-1,1,2},vertical[8]={1,2,2,1,-1,-2,-2,-1};
int count=0;
bool place(int s,int t)
{
    if(s>=0&&s<N&&t>=0&&t<N&&chess[s][t]==0)
     return true;
    return false;    
}

void backtrace(int s,int t,int sum)
{
    if(sum>N*N)
    {
       ::count ++;
    for(int i=0;i<N;i++){
     for(int j=0;j<N;j++)
     cout <<‘ ‘ << chess[i][j];
     putchar(‘/n’);
    }
       system(“pause”);
       return;          
    }    
    else {
      for(int i=0;i<=7;i++)  
      if(place(s+vertical[i],t+horizontal[i])){
         s += vertical[i];
         t += horizontal[i];
         chess[s][t] = sum ;
         backtrace(s,t,sum+1);
         chess[s][t] = 0;
         s -= vertical[i];
         t -= horizontal[i];                                    
      }    
    }
}
int main()
{
   int i,sum=1,start_x,start_y,j;
   for(i=0;i<N;i++)
    for(j=0;j<N;j++)
    chess[i][j] = 0;
   cin >> start_x >> start_y;
   chess[start_x][start_y] = 1;
   backtrace(start_x,start_y,2);
   cout << ::count << endl;
   system(“pause”);
   return 0;     
}

    原文作者:骑士周游问题
    原文地址: https://blog.csdn.net/yellowOri/article/details/5674355
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞