N皇后問題
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 21770 Accepted Submission(s): 9741
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
題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=2553
題解
dfs回溯。由於每行每列每斜線都不能有其它皇后放置,所以固定每行放一個,這樣只需要考慮列和斜線有多少種排列。用數組vis[3][maxn]記錄是否遍歷過該狀態,vis[0]代表同一列,vis[cnt+i]代表135°斜線,vis[cnt-i+n]代表45°斜線,+n能保證數組下標>0。
注意:直接這麼寫會超時,可以打表
#include <iostream>
#include <string.h>
#include <algorithm>
#include <stdio.h>
#include <math.h>
#include <stack>
#include <queue>
#include <vector>
#define INF 0xffffffff
using namespace std;
const int maxn = 15;
int vis[3][4*maxn];
int n;
int tot;
void search(int cur){
if(cur == n){
tot ++;
}
else{
for(int i=0; i<n ;i++){
if(!vis[0][i] && !vis[1][cur+i] && !vis[2][cur-i+n]){
vis[0][i] = 1; vis[1][cur+i] = 1; vis[2][cur-i+n] = 1;
search(cur+1);
vis[0][i] = 0; vis[1][cur+i] = 0; vis[2][cur-i+n] = 0;
}
}
}
}
int main(){
// for(n=0; n<=10; n++){
// memset(vis, 0, sizeof(vis));
// tot = 0;
// search(0);
// printf("%d\n", tot);
// }
int a[] = {0,1,0,0,2,10,4,40,92,352,724};
while(scanf("%d", &n) == 1 && n){
printf("%d\n", a[n]);
}
return 0;
}