1. 程式人生 > 其它 >八皇后經典回溯

八皇后經典回溯

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