1. 程式人生 > >n皇后問題(dfs練習)hdu2553

n皇后問題(dfs練習)hdu2553

題目:
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

用dfs的演算法,這裡要注意,要打表,不然會超時,行數已知,只需要陣列存皇后在第幾列,對角線是否相等用abs(row-i)==abs(x[row]-x[i])判斷:

//
//  queendfs.cpp
//  hdu1240dfs3d
//
//  Created by zhan_even on 2018/11/24.
//  Copyright © 2018年 zhan_even. All rights reserved.
//

#include <iostream>
#include<math.h>
int n, sum;
int x[15];
int result[15] = {0}; //打表
using namespace std;
int place(int row){
    for(int i = 1; i<row; i++){
        //即判斷是否符合條件來放,i表示皇后所在的行數,x[i]表示所在的列數,
        //所以前面那個條件用來判斷兩個皇后是否在對角線上,後面用來判斷是否在同一列上。
        //行數不需要判斷,因為他們本身的i就代表的是行數
        if(abs(row-i)==abs(x[row]-x[i])||x[row]==x[i])
            return 0;
    }
    return 1;
}
void dfs(int h){
    if(h > n) //找到出口
        sum++;
    else{
        for(int i = 1; i<=n; i++){
            x[h]=i;                     //第h個皇后放的列數
            if(place(h))                //判斷是否能放這步
                dfs(h+1);               //能的話進行下一個皇后的放置
        }
    }
    
}
int main(){
    for(int i = 1; i <= 10; i++){
        n = i;
        sum = 0;
        dfs(1);
        result[i] = sum;
    }
    int m;
    while (cin >> m && m) {
        cout << result[m] << endl;;
    }
    return 0;
}