[leetcode 52] N-Queens II

来源:互联网 发布:网络外卖卖爆了的菜品 编辑:程序博客网 时间:2024/05/18 04:01

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

class Solution {public:    int totalNQueens(int n) {        this->res = 0;        this->col = vector<int>(n,0);          this->main_diag = vector<int>(2*n,0);          this->anti_diag = vector<int>(2*n,0);        vector<int> path(n,0);        dfs(path, 0);        return this->res;    }private:    int res;    vector<int> col;    vector<int> main_diag;    vector<int> anti_diag;    void dfs(vector<int> &path, int row) {        const int N = path.size();        if (row == N) {            ++this->res;            return;        }        for (int i = 0; i < N; i++) {            bool ok = col[i] == 0 && main_diag[row+i]==0 && anti_diag[row-i+N]==0;            if(!ok) {                continue;            }            path[row] = i;            col[i] = main_diag[row+i]= anti_diag[row-i+N]= 1;            dfs(path,row+1);            col[i] = main_diag[row+i]= anti_diag[row-i+N]= 0;        }    }    };


0 0