骑士周游 回溯法

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值