1. 程式人生 > >hdu2553 n皇后問題 dfs搜尋 記憶化

hdu2553 n皇后問題 dfs搜尋 記憶化

N皇后問題

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 21710    Accepted Submission(s): 9709


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
Author cgf
Source 不難,測試資料裡重複的很多,因此要打個表記錄一下結果
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
const int maxn = 20;
const int inf = 0x3f3f3f3f;
bool vis[maxn][maxn];
int n,m;
int times[maxn];
int res;
bool check(int x,int y){
    int i;
    for(i=1;i<=n;i++){
        if(!vis[i][y]&&i!=x){
            return false;
        }
    }
    for(i=1;;i++){
        if(x-i==0||y-i==0){
            break;
        }
        if(!vis[x-i][y-i]){
            return false;
        }
    }
    for(i=1;;i++){
        if(x+i>n||y+i>n){
            break;
        }
        if(!vis[x+i][y+i]){
            return false;
        }
    }
    for(i=1;;i++){
        if(x+i>n||y-i==0){
            break;
        }
        if(!vis[x+i][y-i]){
            break;
        }
    }
    for(i=1;;i++){
        if(x-i==0||y+i>n){
            break;
        }
        if(!vis[x-i][y+i]){
            return false;
        }
    }
    return true;
}
void dfs(int x){
    int i;
    if(x>n){
        res++;
    }
    for(i=1;i<=n;i++){
        if(check(x,i)){
            vis[x][i] = false;
            dfs(x+1);
            vis[x][i] = true;
        }
    }
}
int main(){
    memset(times, inf, sizeof(times));
    while(~scanf("%d",&n)&&n){
        if(times[n]!=inf){
            printf("%d\n",times[n]);
            continue;
        }
        memset(vis, true, sizeof(vis));
        res = 0;
        dfs(1);
        times[n] = res;
        printf("%d\n",res);
    }
    
    return 0;
}