We use backtrack to solve these problems. For an N-Queen problem, we use an int array: int[n] to store the position in each row, then, from the first row, place the queen, if it is ok (there are no queens in this row, this column and diagonals),then place the next row, if it is not ok, we use next position in this row. When we finish the last line, then the result is reasonable.
Code for 51-N-Queen
Always use StringBuilder or StringBuffer to avoid "String1 += String2" to save time.
class Solution {
List<List<String>> result ;
int length;
int[] board;
public List<List<String>> solveNQueens(int n) {
if(n==1){
List<String> l = new ArrayList<String>();
l.add("Q");
result = new ArrayList<List<String>>();
result.add(l);
return result;
}
if(n<4)
return new ArrayList<List<String>>();
length = n;
board = new int[n];
result = new ArrayList<List<String>>();
nqueen(0);
return result;
}
private void nqueen(int row){
if(row == length){
List<String> temp = new ArrayList<String>();
for(int i=0; i < length; i++){
StringBuilder sb = new StringBuilder();
for(int j = 0; j < length; j++){
if(board[i] == j)
sb.append('Q');
else
sb.append('.');
}
temp.add(sb.toString());
}
result.add(temp);
return;
}
for(int i = 0; i < length; i++){
board[row] = i;
if(check(row))
nqueen(row+1);
}
}
private boolean check(int row){
for(int i = 0; i < row; i++){
if(board[row] == board[i] || board[row] - board[i] == row -i || board[row] - board[i] == i -row)
return false;
}
return true;
}
}
Code for 52-N-Queen
class Solution {
int result;
int[] board;
int length;
public int totalNQueens(int n) {
if(n<1) return 0;
if(n == 1) return 1;
if(n < 4) return 0;
result = 0;
length = n;
board = new int[n];
nqueen(0);
return result;
}
private void nqueen(int row){
if(row == length){
result++;
return;
}
for(int i = 0; i < length; i++){
board[row] = i;
if(check(row))
nqueen(row+1);
}
}
private boolean check(int row){
for(int i=0; i < row; i++){
if(board[row] == board[i] || board[row]-board[i] == row-i || board[row]-board[i] == i-row)
return false;
}
return true;
}
}