#include <algorithm>
#include <iostream>
using namespace std;
#include<queue>//队列的相关函数调用
#include<stdio.h>
struct node {
int step;//当前步数
int* x;//x[i]:第i个皇后所在的列数
};
int n, num;
bool IsOk(int j, int* x, int i) {//可行条件
//第step+1个皇后有位置可去
//j:当前皇后所在列数 i:第i个皇后
int m;
for (m = 1; m <= i; m++) {//与前面的第j个皇后进行比较
if (j == x[m])return false;//同列
if (abs(m - (i + 1)) == abs(x[m] - j)) return false;
}
return true;
}
void bfs() {//搜索框架
queue <node> q;
node n0, n1, n2;
int i, j;
n0.step = 0;
n0.x = new int[n0.step + 1];
q.push(n0);//初始化,进队列
while (!q.empty()) {
n1 = q.front();//头结点出队列
q.pop();
if (n1.step == n)//出口
{
for (i = 1; i <= n; i++)cout << n1.x[i] << '\t'; cout << endl;
num++;
continue;
}
for (i = 1; i <= n; i++) {
if (IsOk(i, n1.x, n1.step)) {
n2.step = n1.step + 1;//
n2.x = new int[n2.step + 1];
for (j = 1; j < n2.step; j++)n2.x[j] = n1.x[j];
n2.x[n2.step] = i;
q.push(n2);
}//if
}
}
}
int main() {
cout << "请输入皇后个数n:" << endl;
cin >> n;
cout << "该皇后问题的解为:" << endl;
bfs();
printf("共有%d种方法", num);
return 0;
}
队列式分支限界求解n皇后问题
最新推荐文章于 2024-07-13 21:27:21 发布