Leetcode:N-Queens II

Follow up for N-Queens problem.

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

分析:跟N-Queens一样,DFS+Backtracking。

class Solution {
public:
    vector<bool> col;
    vector<bool> main_diag;
    vector<bool> anti_diag;
    
    int totalNQueens(int n) {
        int result = 0;
        if(n == 0) return result;
        
        col = vector<bool>(n, false);
        main_diag = vector<bool>(2*n-1, false);
        anti_diag = vector<bool>(2*n-1, false);
        
        dfs(result, n, 0);
        
        return result;
    }
    
    void dfs(int &result, int n, int row){
        if(row == n){
            result++;
            return;
        }
        for(int j = 0; j < n; j++)
            if(!col[j] && !main_diag[row-j+n-1] && !anti_diag[row+j]){
                col[j] = true;
                main_diag[row-j+n-1] = true;
                anti_diag[row+j] = true;
                dfs(result, n, row+1);
                col[j] = false;
                main_diag[row-j+n-1] = false;
                anti_diag[row+j] = false;
            }
    }
};

 

posted on 2014-08-01 14:03  Ryan-Xing  阅读(223)  评论(0)    收藏  举报