N皇后问题

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;
}

 

因上求缘,果上努力~~~~ 作者:每天卷学习,转载请注明原文链接:https://www.cnblogs.com/BlairGrowing/p/14093323.html

原文地址:https://www.cnblogs.com/BlairGrowing/p/14093323.html