hdu2553 N皇后问题-dfs回溯剪枝+打表
生活随笔
收集整理的這篇文章主要介紹了
hdu2553 N皇后问题-dfs回溯剪枝+打表
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Problem Description
在N*N的方格棋盤放置了N個皇后,使得它們不相互攻擊(即任意2個皇后不允許處在同一排,同一列,也不允許處在與棋盤邊框成45角的斜線上。
你的任務是,對于給定的N,求出有多少種合法的放置方法。
Input
共有若干行,每行一個正整數N≤10,表示棋盤和皇后的數量;如果N=0,表示結束。
Output
共有若干行,每行一個正整數,表示對應輸入行的皇后的不同放置數量。
Sample Input
1
8
5
0
Sample Output
1
92
10
解題思路:
這題我們用了:
進行剪枝,但是沒用,還是超時,所以我們要用打表的方法,在main()中提取算好答案,然后存儲在數組中,等讀取輸入后立刻輸出,而不是等輸入了n,在慢慢計算,會超時。
代碼如下:
#include <iostream> #include <cstring> using namespace std; int ans = 0; int n; const int N = 1010; bool col[N], duijiao1[N], duijiao2[N];void dfs(int x) {if (x > n) {ans++;return ;}for (int y = 1; y <= n; y++) {if (!col[y] && !duijiao1[x + y] && !duijiao2[x - y + n]) {col[y] = duijiao1[x + y] = duijiao2[x - y + n] = true;dfs(x + 1);col[y] = duijiao1[x + y] = duijiao2[x - y + n] = false;}} }int main() {while (cin >> n, n) {memset(col, 0, sizeof(col));memset(duijiao1, 0, sizeof(duijiao1));memset(duijiao2, 0, sizeof(duijiao2));ans = 0;dfs(1);cout << ans << endl;}return 0; }打表大法:
#include <iostream> #include <cstring> using namespace std; int ans = 0; int n; const int N = 1010; bool col[N], duijiao1[N], duijiao2[N]; int biao[15];void dfs(int x) {if (x > n) {ans++;return ;}for (int y = 1; y <= n; y++) {if (!col[y] && !duijiao1[x + y] && !duijiao2[x - y + n]) {col[y] = duijiao1[x + y] = duijiao2[x - y + n] = true;dfs(x + 1);col[y] = duijiao1[x + y] = duijiao2[x - y + n] = false;}} }int main() {for ( n = 1; n <= 10; n++) {ans = 0;memset(col, 0, sizeof(col));memset(duijiao1, 0, sizeof(duijiao1));memset(duijiao2, 0, sizeof(duijiao2));dfs(1);biao[n] = ans;}while (cin >> n, n) {cout << biao[n] << endl;}return 0; }總結
以上是生活随笔為你收集整理的hdu2553 N皇后问题-dfs回溯剪枝+打表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 医院都有什么科
- 下一篇: 今年暑假不AC-贪心