Monday, October 20, 2014

N-Queens II

 almost the same as  N-Queens

class Solution {
public:
    int totalNQueens(int n) {
        int ans=0;
        vector<int> C(n,0);
        search(0,n,C,ans);
        return ans;
       
    }
    void search(int row,int n ,vector<int> &C, int& ans){
        if(row==n){
            ans++;
            return;
        }
        for(int i=0;i<n;i++){
            C[row]=i;
            if(check(row,C))
                search(row+1,n,C,ans);
        }
       
    }
    bool check(int row,vector<int> &C){
        for(int i=0;i<row;i++)
            if(C[i]==C[row]||C[i]-C[row]==row-i||C[row]-C[i]==row-i)
                return false;
        return true;       
    }
};

No comments:

Post a Comment