骑士巡游问题的解法

#include<iostream.h>
#include<stdio.h>

int map[9][9];//用来标记的二维数组
int n=5;//实际计算时的棋盘大小,超过5时计算时间过长,小于5时无解
class Knight{
private:
 int dirx[8];
 int diry[8];
public:
 Knight(){
  dirx[0]=1;diry[0]=2;
  dirx[1]=2;diry[1]=1;
   dirx[2]=1;diry[2]=-2;
    dirx[3]=2;diry[3]=-1;
     dirx[4]=-1;diry[3]=-1;
      dirx[5]=-2;diry[5]=1;
       dirx[6]=-1;diry[6]=-2;
        dirx[7]=-2;diry[7]=-1;
}
private:
 bool judge(int y,int x){
 if(x>0&&x<=n&&y>0&&y<=n&&map[y][x]==0)
  return true;
 else
  return false;
  }
public:
 void set(int y,int x,int t){
  if(t==n*n){
   map[y][x]=t;
   cout<<“一个可能的结果:”<<endl;
   for(int i=1;i<=n;i++){
    for(int j=1;j<=n;j++){
     if(map[i][j]<10)
      cout<<” “;
     cout<<” “<<map[i][j];
    }
    cout<<endl<<endl;
   }
   map[y][x]=0;
   return;
  }
 
  else{
   if(map[y][x]==0){map[y][x]=t;
   int nextt=t+1;
   for(int i=0;i<8;i++){
    if(judge(y+diry[i],x+dirx[i]))
     set(y+diry[i],x+dirx[i],nextt);
   }
   map[y][x]=0;

  }
  }
 }
};
void main(){
Knight *horse=new Knight();//骑士也要走马步
for(int i=1;i<=8;i++)
for(int j=1;j<=n;j++)
horse->set(i,j,1);
delete horse;
}

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