main.cpp
复制代码 代码如下:
#include<iostream>
#include<cstring>
using namespace std;
const int N = 7;
int count = 0;
void QueenPrint(int LayOut[N][N]) //打印结果
{
cout<<"第"<<++count<<"种布局:"<<endl;
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
if(LayOut[i][j] == 1)
{
cout<<' '<<'Q'<<' ';
}
else
{
cout<<' '<<'*'<<' ';
}
}
cout<<endl;
}
cout<<endl;
}
bool Queen(int LayOut[N][N], const int i, const int j) //判断LayOut[i][j]是否适合放置皇后
{
int k1 = 0;
for(; k1 < N; k1++) //判断该行有没有皇后
{
if(LayOut[i][k1] == 1)
{
return false;
}
}
int k2 = 0;
for(; k2 < N; k2++ ) //判断该列有没有皇后
{
if(LayOut[k2][j] == 1)
{
return false;
}
}
int t1 = i,t2 = j; //判断左上有没有皇后
for(;t1 >= 0 && t2 >= 0;t1--,t2-- )
{
if(LayOut[t1][t2] == 1)
{
return false;
}
}
int n1 = i, n2 = j; //判断右上有没有皇后
for(;n1 >= 0 && n2 < N;n1--,n2++ )
{
if(LayOut[n1][n2] == 1)
{
return false;
}
}
return true;
}
/*
void EightQueen(int LayOut[N][N],int i, int j) // i为行,j为列
{
if( i < N )
{
if( j < N)
{
if(Queen(LayOut,i,j))
{
LayOut[i][j] = 1;
j = 0;
EightQueen(LayOut,i+1, j);
}
else
{
EightQueen(LayOut,i, j+1);
}
}
}
else
{
QueenPrint(LayOut);
}
}*/
void EightQueen(int LayOut[N][N],int i) // i为行
{
if( i == N)
{
QueenPrint(LayOut);
//memset( LayOut, 0, sizeof(LayOut));
}
else
{
int j = 0;
for( ; j < N; j++ )
{
if( Queen( LayOut, i, j))
{
LayOut[i][j] = 1;
EightQueen( LayOut,i+1);
LayOut[i][j] = 0;
}
}
}
}
int main()
{
int LayOut[N][N];
memset( LayOut, 0, sizeof(LayOut));
EightQueen(LayOut,0);
cout<<"共"<<count<<"中结果!"<<endl;
return 0;
}