52. N-Queens II (Array; Back-Track)

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) {
        result = 0;
        if(n==0) return result;
        
        vector<int> flag(n,-1); //每行的Q出现在哪列
        backTracking(n, flag, 0);
        return result;

    }   
    
    void backTracking(int n, vector<int>& flag, int depth){ //depth is the line number
        if(depth==n){
            result++;
            return;
        }
        
        for(int i = 0; i < n; i++){ //traverse column
            if(check(n,flag, depth, i)) {
                flag[depth] = i;
                backTracking(n,flag,depth+1);
                flag[depth] = -1; // back track
            }
        }
    }
    
    bool check(int n, vector<int>& flag, int i, int j){
        for(int k = 0; k < i; k++){
            if(flag[k] < 0) continue;//no Q in this column
            if(flag[k]==j) return false;//check columns
            if(abs(i-k)==abs(j-flag[k])) return false; //check cross lines
        }
        return true;
    }
private: 
    int result;
};

 

posted on 2015-10-06 12:25  joannae  阅读(183)  评论(0编辑  收藏  举报

导航