Monday, November 25, 2013

LeetCode Problem : N-Queens II

Problem


Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.

Code

bool isValid(const vector<string> &board,int i,int j,int n)
{
    int steps = min(i,j);
    for(int k = 1;k <= steps; ++k){
        if(board[i - k][j - k] == 'Q')
            return false;
    }
    steps = min(n - 1 - j,i);
    for(int k = 1;k <= steps; ++k){
        if(board[i - k][j + k] == 'Q')
            return false;
    }
    for(int k = 0;k < i; ++k){
    if(board[k][j] == 'Q')
        return false;
    }
    return true;
}
void snq_r1(vector<string> &board,int row,int n,int &result)
{
    if(row == n)
    {
        ++result;
        return;
    }
    for(int j = 0;j < n; ++j){
        if(isValid(board,row,j,n)){
            board[row][j] = 'Q';
            snq_r1(board,row + 1,n,result);
            board[row][j] = '.';
        }
    }
}
int tnq(vector<string> &board,int n)
{
    int count = 0;
    for(int j = 0;j < n/2; ++j){
        board[0][j] = 'Q';
        int result = 0;
        snq_r1(board,1,n,result);
        count += 2*result;
        board[0][j] = '.';
    }
    if(n % 2 == 1){
        board[0][n/2] = 'Q';
        int result = 0;
        snq_r1(board,1,n,result);
        count += result;
        board[0][n/2] = '.';
    }
    return count;
}
int totalNQueens(int n) {
    // IMPORTANT: Please reset any member data you declared, as
    // the same Solution instance will be reused for each test case.
    string str(n,'.');
    vector<string> board(n,str);
    return tnq(board,n);
}

No comments:

Post a Comment