//
//Description: N后问题(回溯法)
//
#include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;
int n;//皇后个数
int x[100];//当前解
static long sum;//当前已找到的可行方案数
bool place(int k)
{
for (int j = 1; j<k; j++)
{
if ((abs(k - j) == abs(x[j] - x[k])) || (x[j] == x[k]))
return false;
}
return true;
}
void backtrack(int t)
{
if (t>n)
{
sum++;
cout << " 第 " << setw(2) << sum << " 个可行解:";
for (int i = 1; i <= n; i++)
{
cout << x[i] << " ";
}
cout << endl;
}
else
for (int i = 1; i <= n; i++)
{
x[t] = i;
if (place(t))
backtrack(t + 1);
}
}
long nQueen(int nn)
{
n = nn;
sum = 0;
for (int i = 1; i <= n; i++)
{
x[i] = 0;
}
backtrack(1);
return sum;
}
void main()
{
cout << "\n\t===============N后问题(回溯法)=================\n";
cout << "Please enter the numbers of Queens:" << endl;
cin >> n;
nQueen(n);
cout << "欲在" << n << "×" << n << "的棋盘上放置满足条件的" << n << "个皇后,可以得到解的个数为 " << sum << endl;
}
n后问题(回溯法)
最新推荐文章于 2024-01-20 20:51:42 发布