解法一:
class Solution {
public static List<List<String>> output;
public List<List<String>> solveNQueens(int n) {
output = new ArrayList<>();
int[] result = new int [n];
place(0, n, result);
return output;
}
private static void place(int row, int n, int[] result){
if (row == n){
show(result);
return;
}
for (int column = 0; column < n; column++){
if (isValid(row, column, result)){
result[row] = column;
place(row + 1, n, result);
}
}
}
private static boolean isValid(int row, int col, int[] result){
for (int i = 0; i < row; i++){
if (result[i] == col) return false;
if (row - i == Math.abs(col - result[i])) return false;
}
return true;
}
private static void show(int[] result){
List<String> one = new ArrayList<>();
for (int row = 0; row < result.length; row++){
StringBuilder str = new StringBuilder();
for (int column = 0; column < result.length; column++){
if (column == result[row]){
str.append("Q");
}else{
str.append(".");
}
}
one.add(str.toString());
}
output.add(one);
}
}
解法二:
class Solution {
private int[] queens;
boolean[] cols;
boolean[] leftTop;
boolean[] rightTop;
public List<List<String>> output;
public List<List<String>> solveNQueens(int n) {
output = new ArrayList<>();
queens = new int[n];
cols = new boolean[n];
leftTop = new boolean[(n << 1) - 1];
rightTop = new boolean[(n << 1) - 1];
place(0);
return output;
}
void place(int row) {
if (row == cols.length) {
show();
return;
}
for (int col = 0; col < cols.length; col++) {
if (cols[col]) continue;
int ltIndex = row - col + cols.length - 1;
if (leftTop[ltIndex]) continue;
int rtIndex = row + col;
if (rightTop[rtIndex]) continue;
cols[col] = leftTop[ltIndex] = rightTop[rtIndex] = true;
queens[row] = col;
place(row + 1);
cols[col] = leftTop[ltIndex] = rightTop[rtIndex] = false;
}
}
private void show(){
List<String> one = new ArrayList<>();
for (int row = 0; row < queens.length; row++){
StringBuilder str = new StringBuilder();
for (int column = 0; column < queens.length; column++){
if (column == queens[row]){
str.append("Q");
}else{
str.append(".");
}
}
one.add(str.toString());
}
output.add(one);
}
}