queen8.cpp

来自「分别用面向过程、面向对象和函数式程序设计的方法解决八皇后问题。 附报告」· C++ 代码 · 共 74 行

CPP
74
字号
#include    <iostream>
using namespace   std;

bool  cols[8];
bool  ldiag[20];
bool  rdiag[20];

int   pos[8];
int   cntall;

int   init()
{
      cntall = 0;
      memset( cols,0,sizeof( cols) );
      memset( ldiag,0,sizeof( ldiag) );
      memset( rdiag,0,sizeof( rdiag) );
      return 0;
      }
      
int   print_queens()
{
      cntall++;
      cout << "Solution No . " << cntall << ":\n";
      for( int i = 0 ; i < 8 ; i++)
      {
           cout << "(";
           for( int j = 0 ; j < 7 ; j++)
                if( j == pos[i] ) cout << "Q ";
                else  cout << "* ";
           if( pos[i] == 7 ) cout << "Q)\n";
           else       cout << "*)\n";
       }
       cout << endl;
           
      }      
      
int   tryQueen( int cnt , int trycol )
{
      if( cnt > 7 )
      {
          if( trycol == 0 ) print_queens();
          return 0;
      }
      
      if( cols[ trycol ] == 1 ) return 0;
      if( ldiag[trycol+cnt] == 1 ) return 0;
      if( rdiag[10-trycol+cnt] == 1 ) return 0; 
      
      cols[ trycol ] = 1;
      ldiag[trycol+cnt] = 1;
      rdiag[10-trycol+cnt] = 1;
      pos[ cnt ] = trycol;
      
      for( int i = 0; i < 8; i++)  tryQueen( cnt+1 , i );

      cols[ trycol ] = 0;
      ldiag[trycol+cnt] = 0;
      rdiag[10-trycol+cnt] = 0;
      
      return 0;
      }
      
      


int   main()
{
      init();
      for( int i = 0; i < 8; i++)
           tryQueen( 0 , i );
      system("pause");
      return 0;
      }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?