八皇后及N皇后问题

#include <iostream>
using namespace std;
char data[ 8 ][ 8 ]; //chess(double dimensional array)
int a[ 8 ];   //column(列)
int b[ 15 ];  //主对角线(左上至右下)
int c[ 15 ];  //从对角线(右上至左下)
int count = 0;
 
void eightQueens( int );
void output( const int [][ 8 ], int );
 
int main()
{
 int i, j;
 
 for( i = 0; i < 15; ++i ) //主、从对角线
  b[ i ] = c[ i ] = 0; //表示安全

 for( i = 0; i < 8; ++i )//chess
 {
  a[ i ] = 0;    //i列安全
  for( j = 0; j < 8; ++j )
   data[ i ][ j ] = 0;
 }
 
 eightQueens( 0 );

 cout << "/ncount = " << count << endl;
 return 0;
}
 
void eightQueens( int line )
{
 if( 8 == line )//八个皇后安置就位,输出
 {
  output( data, 8 );
  cout << endl;
  return;
 }
 

 for( int column = 0; column < 8; ++column )
 {
  if( 0 == a[ column ] && 0 == b[ line - column + 7 ] && 0 == c[ line + column ] )
  {
   data[ line ][ column ] = 1; //安置皇后
   a[ column ] = 1;   //此列被占
   b[ line - column + 7 ] = 1; //主对角线被占
   c[ line + column ] = 1;  //从对角线被占
   eightQueens( line + 1 ); //下一个皇后
   //重置
   data[ line ][ column ] = 0;
   a[ column ] = 0;
   b[ line - column + 7 ] = 0;
   c[ line + column ] = 0;
  }
 }
}
 
//output chess
void output( const int data[][ 8 ], int size )
{
 for( int i = 0; i < size; ++i )
 {
  for( int j = 0; j < size; ++j )
   cout << data[ i ][ j ] << ' ';
  cout << endl;
 }
 ++count;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值