Problem Description
在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。
你的任务是,对于给定的N,求出有多少种合法的放置方法。
你的任务是,对于给定的N,求出有多少种合法的放置方法。
Input
共有若干行,每行一个正整数N≤10,表示棋盘和皇后的数量;如果N=0,表示结束。
Output
共有若干行,每行一个正整数,表示对应输入行的皇后的不同放置数量。
Sample Input
1 8 5 0
Sample Output
1 92 10
#include <cstdio>
#include <cstring>
#define N 15
int n, count;
int ans[N];
bool column[N], left[2 * N + 5], right[2 * N + 5];
void dfs(int i)
{
if (i > n)
{
count++;
return;
}
for (int j = 1; j <= n; j++)
if (column[j] && left[i + j] && right[i - j + N])
{
column[j] = false; left[i + j] = false; right[i - j + N] = false;
dfs(i + 1);
column[j] = true; left[i + j] = true; right[i - j + N] = true;
}
}
int main()
{
memset(ans, -1, sizeof(ans));
while (scanf("%d", &n), n)
{
if (~ans[n])
{
printf("%d\n", ans[n]);
continue;
}
count = 0;
memset(column, true, sizeof(column));
memset(left, true, sizeof(left));
memset(right, true, sizeof(right));
dfs(1);
ans[n] = count;
printf("%d\n", ans[n]);
}
return 0;
}