51. N-Queens
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.."]
]
Related issue: 52 N-Queens II backtacking
public class Solution {
List<List<String>> res = new ArrayList<>();
public List<List<String>> solveNQueens(int n) {
char[][] board = new char[n][n];
for(int i=0; i< n;i++){
for(int j=0; j< n; j++){
board[i][j] = '.';
}
}
bt(board, 0, n);
return res;
}
private void bt(char[][] board, int row, int n){
if(row == n){
//save into database.
List<String> t = new ArrayList<>();
for(char[] s : board){
t.add(new String(s));
}
res.add(t);
}
for(int col=0; col < n; col++){
if(isValid(board, row, col)){ // if is not valid, then there is no solution added.
board[row][col] = 'Q';
bt(board, row+1, n);
board[row][col] = '.';
}
}
}
private boolean isValid(char[][] board, int row, int col){
for(int i= row-1; i >=0; i--){
if(board[i][col] == 'Q' )return false;
}
for(int i=row-1, j=col-1; i >=0 && j>=0; i--,j--){
if(board[i][j] == 'Q') return false;
}
for(int i=row-1, j=col+1; i>=0 && j<board.length; i--,j++){
if(board[i][j] == 'Q') return false;
}
return true;
}
}