1、八皇后问题
#include "stdafx.h"
#include <math.h>
class Queen
{
friend int nQueen(int);
private:
//用可行性约束函数Place()可剪去不满足行,列和斜线约束的子树。
bool Place(int k);
void Backtrack(int t);
int n; //the num of Queens
int *x; //当前解
long sum; //当前已找到的可行方案数
};
bool Queen::Place(int k)
{
for(int j=1; j<k; j++)
{
if(abs(k-j) == abs(x[j]-x[k]) || (x[j] == x[k]) || (k+j == x[j]+x[k]) || j==k)
return false;
}
return true;
}
void Queen::Backtrack(int t)
{
//如果列可以到尾部的话,就代表有可行性解
if(t>n) sum++;
else
for(int i=1; i<=n; i++)
{
x[t]=i;
if(Place(t))
Backtrack(t+1);
}
}
int nQueen(int n)
{
Queen X;
X.n = n;
X.sum = 0;
int *p = new int[n+1];
for(int i=0; i<=n; i++)
p[i] = 0;
X.x = p;
X.Backtrack(1);
delete []p;
return X.sum;
}
int _tmain(int argc, _TCHAR* argv[])
{
nQueen(4);
return 0;
}