对于n(n>=4)皇后问题:
任意两个Queens不能同行同列,而且不能共对角线(主对角,副对角)
其中主对角行列相减的绝对值是相等的
副对角线行列相加是相等的
本题对于n*n格的棋盘中有多少种满足上述条件的解:
本题首先设置全局的计数count,
然后设置相应的剪枝项
colmun
main_diag
anti_diag
然后使用深度优先搜索法:
/*
输出N皇后问题的解数
*/
#include<iostream>
#include<vector>
using namespace std;
class NQUEEN
{
public:
int N_queen(int n)
{
this->count = 0;
this->colmun = vector<int>(n, 0);
this->main_diag = vector<int>(2 * n, 0);
this->anti_diag = vector<int>(2 * n, 0);
vector<int>C(n, 0);//C[i]表示第i行皇后所在的列数
dfs(C, 0);
return this->count;
}
private:
int count;//计数
vector<int>colmun;//
vector<int>main_diag;//主对角线占据的位置
vector<int>anti_diag;//副对角线占据的位置
void dfs(vector<int>&C, int row)
{
const int N = C.size();
if (N == row)
{
++this->count;
return;
}
//剪枝,一行一行的试
for (int j = 0; j < N; j++)
{
const bool ok = colmun[j] == 0 && main_diag[row - j + N] == 0 && anti_diag[row + j] == 0;
if (!ok) continue;
C[row] = j;
colmun[j] =main_diag[row - j + N] =anti_diag[row + j] =1;
dfs(C, row + 1);
colmun[j] = main_diag[row - j + N] = anti_diag[row + j] = 0;
}
}
};
int main()
{
NQUEEN q1;
int n;
cout << "输入N-Queen个数N=";
cin >> n;
cout << "共有" << q1.N_queen(n) << "种解。" << endl;
system("pause");
return 0;
}