在8*8格的国际象棋上摆放八个皇后,即任意两个皇后都不能处于同一行、同一列或同一斜线上,求解排列方法
#include<iostream>
#include<cstdlib>
using namespace std;
int count1 = 0;
int Q[8];
void EightQuene(int n)
{
//cout << "进入主程序 " << n << endl;
if (n == 8)
{
cout << "找到了第 " << ++count1 << " 个解" << endl;
for (int i = 0; i < 8; i++)
cout << Q[i] << " ";
cout << endl;
}
for (int i = 0; i < 8; i++)//第n列,从第0行到第7行,找寻是否有匹配的元素
{
//cout << "n= " << n << endl;
Q[n] = i;
int collision = 0;
for (int j = 0; j < n; j++) //与第n列之前的所有元素比对,判断是否冲突
if (Q[n] == Q[j] || abs(Q[n] - Q[j]) == n - j)
{
//cout << "冲突了" << endl;
collision = 1;
}
//cout << "collison= " << collision << endl;
if (collision == 0)
EightQuene(n + 1);
}
}
int main()
{
EightQuene(0);
system("pause");
return 0;
}