HDOJ_ACM_N皇后问题
2013-04-21 09:41
204 查看
[align=left]Problem Description[/align] 在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。 你的任务是,对于给定的N,求出有多少种合法的放置方法。 |
[align=left]Input[/align] 共有若干行,每行一个正整数N≤10,表示棋盘和皇后的数量;如果N=0,表示结束。 |
[align=left]Output[/align] 共有若干行,每行一个正整数,表示对应输入行的皇后的不同放置数量。 |
[align=left]Sample Input[/align]1 8 5 0 |
[align=left]Sample Output[/align]1 92 10 |
Code View Code #include <stdio.h> #include <math.h> #include <stdlib.h> int q[11]; //q[1] means the coordinate of queue is (1, q[1]) int result[11];//to save the time, so record the previous time int n; int check(int k) //check if the kth queen is conflict with previous ones { int i; i = 1; while (i < k) { //k - i == abs(q[k] - q[i]) means the current queen is not 45° with other queens if (q[i] == q[k] || k - i == abs(q[k] - q[i])) return 0; i++; } return 1; } int count; //record the count of rank int flag; void DFS(int step) { int i, j, k; if (step == n + 1) count++; else { for (i = 1; i <= n; i++) { q[step] = i; if (check(step) == 0) continue; DFS(step + 1); } } } int main() { while (scanf("%d", &n) != EOF && n) { //memset(); count = 0; if (result == 0) { DFS(1); result = count; } printf("%d\n", result ); } return 0; } |
u can find that the first one use least time. |
[align=left]Recommend[/align] lcy |
相关文章推荐
- HDOJ 2553 N皇后问题 杭电 ACM
- 杭电OJ(HDOJ)2553题:N皇后问题(回溯法)
- hdoj_2553N皇后问题
- HDOJ N皇后问题
- (DFS)N皇后问题--HDOJ
- hdoj 2553 N皇后问题
- hdoj 2553 N皇后问题
- HDOJ 2553 N皇后问题
- HDOJ 2553 N皇后问题(递归)
- HDOJ-2553 N皇后问题
- HDOJ 2553 N皇后问题(dfs+打表)
- hdoj 2553 N皇后问题
- HDOJ 2553 N皇后问题
- HDOJ - 2553 N皇后问题
- ACM: dfs题 poj 1321 (n皇后问题)
- 杭电 acm 2553 N皇后问题
- HDOJ N皇后问题 2553【回溯搜索】
- hdoj-2553 n 皇后问题【递归】
- hdoj 2553 N皇后问题 【DFS】
- HDOJ 题目2553 N皇后问题(dfs)