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.."] ]
import java.util.ArrayList;
public class Solution {
public ArrayList<String[]> solveNQueens(int n) {
ArrayList<String[]> result = new ArrayList<String[]>();
if(n <= 0) return result;
int[] columns = new int[n];
helper(n, result, columns, 0);
return result;
}
private void helper(int n, ArrayList<String[]> result, int[] columns, int row){
if(row == n){
String[] list = new String[n];
for(int i = 0; i < n; i++){
StringBuffer sb = new StringBuffer();
for(int j = 0; j < n; j++){
if(columns[i] == j){
sb.append("Q");
} else {
sb.append(".");
}
}
list[i] = sb.toString();
}
result.add(list);
return;
}
for(int i = 0; i < n; i++){
if(isValid(columns, row, i)){
columns[row] = i;
helper(n, result, columns, row + 1);
}
}
}
private boolean isValid(int[] columns, int row1, int column1){
for(int row2 = 0; row2 < row1; row2++){
if(columns[row2] == column1) return false;
int diff = Math.abs(column1 - columns[row2]);
if(diff == (row1 - row2)) return false;
}
return true;
}
}