八皇后经典回溯

发布时间:2022-06-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了八皇后经典回溯脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
#include<iostream>
#include<vector>
using namespace std;
bool is_not_under_attack(int row, int col, int n,
    vector<int> & rows,
    vector<int> & hills,
    vector<int> & dales) {
    int res = rows[col] + hills[row - col + n-1] + dales[row + col];
    return (res == 0) ? true : false;
}
int backtrack(int row, int count, int n,
    vector<int> & rows,
    vector<int> & hills,
    vector<int> & dales) {
    for (int col = 0; col < n; col++) {
        if (is_not_under_attack(row, col, n, rows, hills, dales)) {
            // place_queen
            rows[col] = 1;
            hills[row - col + n-1] = 1;  // "hill" diagonals
            dales[row + col] = 1;   //"dale" diagonals    

            // if n queens are already placed
            if (row + 1 == n) count++;
            // if not proceed to place the rest
            else count = backtrack(row + 1, count, n,
                rows, hills, dales);

            // remove queen
            rows[col] = 0;
            hills[row - col + n-1] = 0;
            dales[row + col] = 0;
        }
    }
    return count;
}
int totalNQueens(int n) {
    vector<int> rows(n);
    vector<int> hills(2*n-1);
    vector<int> dales(2*n-1);
    return backtrack(0, 0, n, rows, hills, dales);
}
int main(void) {
    cout << totalNQueens(8) << endl;
    return 0;
}

脚本宝典总结

以上是脚本宝典为你收集整理的八皇后经典回溯全部内容,希望文章能够帮你解决八皇后经典回溯所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: