⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 queen8.cpp

📁 分别用面向过程、面向对象和函数式程序设计的方法解决八皇后问题。 附报告
💻 CPP
字号:
#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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -