先阐述一下n皇后问题,在一个n行n列的棋盘上放置n个皇后,任两个皇后都不能处于同一条横行、纵行或斜线上。
此问题可以转换为全排列问题,对于下图,可将下图皇后的位置记录为一维数组{4,2,8,5,7,1,3,6},数组的第一个元素4代表的意思是第一列第4行有一个皇后,数组的第三个元素8代表的是第三列,第八行有一个皇后。这样求1~n的全排列,得到的皇后放置方案是不在同一行也不在同一列的,之后再去除对角线上的不合理方案即可。
#include "iostream"
using namespace std;
const int length = 100;
int hashTable[length] = { false };
void hasha(int index, int n, int *pcount,int *P);
int main()
{
int count = 0;//count用来记录方案的数量
int* pcount = &count;
cout << *pcount << endl;
cout << "请输入n代表n皇后问题n<=length-1,length=100" << endl;
int n;//表示n皇后
cin >> n;
int P[length];//P数组存储某一组排列
cout << "方案" << endl;
hasha(1, n, pcount, P);
cout << "共有"<<*pcount<<"种方案"<<endl;//这个计算总数的有问题
system("pause");
return 0;
}
void hasha(int index, int n, int *pcount,int *P)
{
if (index == n + 1)
{
bool flag = true;
for (int i = 1; i <= n; i++)
{
for (int j = i + 1; j <= n; j++)
{
// cout << "i=" << i << "j=" << j << endl<<"P[i]=" << P[i] << "P[j]=" << P[j] << endl;
if (abs(i - j) == abs(P[i] - P[j]))
{
flag = false;
}
}
}
if (flag)
{
*pcount=*pcount+1;
for (int i = 1; i <= n; i++)
cout << P[i];
cout << endl;
cout << *pcount << endl;
}
return ;
}
for (int x = 1; x <= n; x++)
{
if (hashTable[x] == false)
{
P[index] = x;//需要注意的是我P数组是从下标1开始存储的,所以n皇后,开辟的长度为n+1
hashTable[x] = true;
hasha(index + 1, n, pcount,P);
hashTable[x] = false;
}
}
}