N皇后问题:在一个N行N列的棋盘上,放N个皇后,并且保证任意两个皇后不在同一行、同一列、同一对角线上,共有多少种放法?
解决方法见代码。函数nonconflict用于判断皇后之间是否有攻击现象;函数queencore用于递归计算符合条件的放法;queens函数是接口函数。
state数组第i个元素表示第i行,state[i]表示第state[i]列,即state数组表示第i行、第state[i]列放一个皇后。
bool nonconflict(int* state, int len, int next)
{
for(int i = 0; i < len; i++)
if(*(state + i) == next || abs(*(state + i) - next) == len - i)
return false;
return true;
}
int queencore(int* state, int row, int n)
{
if(row == n)
return 1;
int result = 0;
for(int i = 0; i < n; i++)
{
if(nonconflict(state, row, i))
{
*(state + row) = i;
result += queencore(state, row + 1, n);
}
}
return result;
}
int Queens(int n)
{
if(n < 1)
return 0;
int* state(new int[n]);
int count(0);
count = queencore(state, 0, n);
delete state;
return count;
}