1. 程式人生 > 實用技巧 >前端開發Docker快速入門(二)製作映象並建立容器

前端開發Docker快速入門(二)製作映象並建立容器

N皇后問題

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

回溯和剪枝

source:http://acm.hdu.edu.cn/showproblem.php?pid=2553

#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int n, tot = 0;
int col[12] = {0};
bool check(int c, int r) {              //檢查是否和已經放好的皇后衝突
    for(int i = 0; i < r; i++)
        if(col[i] == c || (abs(col[i]-c) == abs(i -r))) //取絕對值
            return false;
    return true
; } void DFS(int r) { //一行一行地放皇后,這一次是第r行 if(r == n) { //所有皇后都放好了,遞迴返回 tot++; //統計合法的棋局個數 return; } for(int c = 0; c < n; c++) //在每一列放皇后 if(check(c, r)){ //檢查是否合法 col[r] = c; //在第r行的c列放皇后
DFS(r+1); //繼續放下一行皇后 } } int main() { int ans[12]={0}; for(n = 1; n <= 10; n++){ //算出所有n皇后的答案。先打表不然會超時 memset(col,0,sizeof(col)); //清空,準備計算下一個N皇后問題 tot = 0; DFS(0); ans[n] = tot; //打表 } while(cin >> n) { if(n==0) return 0; cout << ans[n] << endl; } return 0; }