Monday, November 25, 2013

LeetCode Problem : N-Queens

Problem


The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

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_r(vector<string> &board,int row,int n,vector<vector<string> > &result)
{
    if(row == n)
    {
        result.push_back(board);
        return;
    }
    for(int j = 0;j < n; ++j){
        if(isValid(board,row,j,n)){
            board[row][j] = 'Q';
            snq_r(board,row + 1,n,result);
            board[row][j] = '.';
        }
    }
}
vector<vector<string> > solveNQueens(int n) {
    // IMPORTANT: Please reset any member data you declared, as
    // the same Solution instance will be reused for each test case.
    vector<vector<string> > result;
    string str(n,'.');
    vector<string> board(n,str);
    snq_r(board,0,n,result);
    return result;
}

No comments:

Post a Comment