HDU 2553 N皇后问题 (DFS)

来源:互联网 发布:云计算的三种类型 编辑:程序博客网 时间:2024/04/28 11:36
Problem Description
在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。
你的任务是,对于给定的N,求出有多少种合法的放置方法。

 

Input
共有若干行,每行一个正整数N≤10,表示棋盘和皇后的数量;如果N=0,表示结束。
 

Output
共有若干行,每行一个正整数,表示对应输入行的皇后的不同放置数量。
 

Sample Input
1850
 

Sample Output
19210
#include <cstdio>#include <cstring>#define N 15int 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;}

0 0