public class Solution {
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] = '.';
}
}
List<List<String>> rst = new ArrayList<>();
dfs(board, 0, rst);
return rst;
}
private void dfs(char[][] board, int colIndex, List<List<String>> rst) {
if (colIndex == board.length) {
rst.add(construct(board));
return;
}
for (int i = 0; i < board.length; i++) {
if (validate(board, i, colIndex)) {
board[i][colIndex] = 'Q';
dfs(board, colIndex + 1, rst);
board[i][colIndex] = '.';
}
}
}
private boolean validate(char[][] board, int x, int y) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < y; j++) {
if (board[i][j] == 'Q' && (y - j == x - i || y - j == i - x || i == x)) return false;
}
}
return true;
}
private List<String> construct(char[][] board) {
List<String> level = new ArrayList<>();
for (int i = 0; i < board.length; i++) {
String s = new String(board[i]);
level.add(s);
}
return level;
}
}