N-Queens
Mar 20 '12
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.."] ]
class Solution {
public:
vector<vector<string> > solveNQueens(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<string> > res;
string temp(n,'.');
vector<string> cur(n, temp);
queenRec(res, cur, n, 0);
return res;
}
private:
void queenRec(vector<vector<string>>& res, vector<string>& cur, int n, int level) {
if(level==n) {
res.push_back(cur);
return;
}
for(int i=0; i<n; i++) {
if( check(cur, level, i) ) {
cur[level][i]='Q';
queenRec(res, cur, n, level+1);
cur[level][i]='.';
}
}
}
bool check(const vector<string>& cur, int row, int col) {
int n= cur.size();
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
if(cur[i][j]=='Q' && (i==row || j==col ||row-i==abs(col-j))) return false;
}
}
return true;
}
};
public class Solution {
public ArrayList<String[]> solveNQueens(int n) {
// Start typing your Java solution below
// DO NOT write main() function
char[][] res = new char[n][n];
for(int i=0; i<n; i++) {
for(int j=0;j<n;j++) {
res[i][j] = '.';
}
}
boolean[][] board = new boolean[n][n];
ArrayList<String[]> resList = new ArrayList<String[]>();
qRec(resList,res,board, 0);
//convert char[][] to ArrayList<String[]>;
return resList;
}
private void qRec(ArrayList<String[]> resList, char[][] res, boolean[][] board ,int level){
int n = res.length;
if( level >= n) {
String[] ss = new String[n];
for(int i=0;i<n;i++) {
ss[i] = new String(res[i]);
}
resList.add(ss);
return;
}
for(int i=0; i<n; i++) {
res[level][i] = 'Q';
board[level][i] = true;
if( check( res,board, i, level) ) {
qRec(resList, res, board, level+1);
}
board[level][i] = false;
res[level][i] = '.';
}
}
private boolean check( char[][] res, boolean[][] board, int col ,int line){
int n = res.length;
for(int j=0; j<line; j++) {
if( board[j][col] == true )
return false;
for(int k=0; k<n; k++) {
if( board[j][k]==true && line-j==Math.abs(col-k))
return false;
}
}
return true;
}
}