<OJ_Sicily>N_Queen Problem

40 篇文章 0 订阅

Description

Given N queens on an N*N chess board, find the number of ways of placing these queens so that they will not attack each other.

Input

There are multiple cases. For each case, there is only one line given the number of queens N (1<=N<=9).

Output

For each case, output the number of all possible placements of queens.

问题解释:对于一个N*N的棋盘中放N个皇后,使得每个皇后彼此之间不能攻击(同行,同列,同对角线都会攻击),求解所有解的总数

输入:皇后个数N

输出:N个皇后共存的所有放置方法数

解题思路:对于这个问题,由于每个皇后不能同行同列同对角线,因此每一列都有且只能存在一个皇后,用数组queens_N来记录每一列皇后所在的行号,也就是queens_N[0]表示第0列皇后所在的行数为queens_N[0],最终的解将存在queens_N[0]中

#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;

class Queen{         //创建一个Queen类
public:
    int count;
    Queen(int n){
        N = n;
        count = 0;
        memset(queens_N, 0, sizeof(queens_N));
    };
    bool Place(int k);  
    void Backtrack(int t);  //回溯求解
private:
    int N;
    int queens_N[9];
};
bool Queen::Place(int k){         //寻找第k列的位置,要是没有位置了返回false,要是有位置,返回true
    for (int j = 0; j < k; j++) {  //检查放在k位置的皇后是否可行
        if (queens_N[k] == queens_N[j] || abs(k-j) == abs(queens_N[j] - queens_N[k])) return false;
    }
    return true;
}
void Queen::Backtrack(int t){     //回溯方法求解
    if (t >= N) {
        count ++;
    }
    else{
        for (int i = 0; i < N; i++) {
            queens_N[t] = i;
            if (Place(t)) {
                Backtrack(t+1);
            }
        }
    }
}
int main(int argc, const char * argv[]) {
    // insert code here...
    int N;
    while (cin >> N) {
        Queen queen(N);     //创建N黄后这个类
        queen.Backtrack(0);  //从第一个位置加上回溯
        cout << queen.count << endl;
    }
    return 0;
}                                 


后记:

使用的是回溯算法来求解N皇后问题,这个过程其实是深度遍历,当当前路径不可行的时候就进行回溯,要是可行就进行递归获得最终可行解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值