nei.cpp
上传用户:cctqzzy
上传日期:2020-11-17
资源大小:1k
文件大小:2k
源码类别:

压缩解压

开发平台:

Visual C++

  1. #include<iostream>
  2. using namespace  std;
  3. int row[8]={-1,-2,-2,-1,1,2,2,1,};   /*8个方向上的x增量*/
  4. int col[8]={2,1,-1,-2,-2,-1,1,2};  /*8个方向上的y增量*/
  5. int h[8][8];                             /*记录走的路径*/
  6. int num;                                 /*记录方案个数*/ 
  7. void coutSolution();
  8. void try1(int x,int y,int i); 
  9. int main()
  10. {
  11. int row,col;
  12.  
  13. num=0;
  14. for(row=0;row<=7;row++)
  15. for(col=0;col<=7;col++)
  16. h[row][col]=0;
  17. int m,n;
  18. cout<<"输入骑士最开始的位置行:列:";
  19. cin>>m;
  20. cin>>n;
  21.  
  22.   h[m-1][n-1]=1;
  23.  //h[0][0]=1;  
  24.    try1(m-1,n-1,2);
  25.   
  26.    /*输出总方案数*/ 
  27.   cout<<"总方案数为%d"<<num; 
  28.   
  29.    //system("pause");
  30. return 0;
  31. /*从(x,y)出发,为第i步找合适位置*/ 
  32. void try1(int x,int y,int i)
  33.     int dir,u,v;
  34.     
  35.     if (i>64) /*已经走完64步,则统计方案个数,打印方案,跳出递归*/
  36.     {
  37.         num++;
  38. if(num==1)
  39.     coutSolution();  
  40.     }     
  41.     else
  42.         for(dir=0;dir<=7;dir++) /*依次试遍8个方向*/
  43.         {
  44.             u=x+row[dir]; /*得到的新坐标*/ 
  45.             v=y+col[dir];
  46.             if ((u>=0) && (u<=7) && (v>=0) && (v<=7) && (h[u][v]==0))/*如果新坐标在棋盘上,并且这一格可以走*/
  47.             {
  48.                 h[u][v]=i;/*占据位置[u,v]*/ 
  49.                 try1(u,v,i+1); 
  50.                 h[u][v]=0;
  51.             }
  52.         } 
  53. /*打印方案*/
  54. void coutSolution()
  55. {
  56.     int row,col;
  57.   
  58.     for(row=0;row<=7;row++)
  59. for(col=0;col<=7;col++)
  60.          cout<<h[row][col]<<' ';
  61.       cout<<"n";
  62.     }            
  63.     cout<<"nn";