class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> res = new ArrayList();
String[] board = new String[n];
boolean[] cols = new boolean[n];
boolean[] diagnol1 = new boolean[2 * n];
boolean[] diagnol2 = new boolean[2 * n];
recSolveNQueens(0, n, cols, diagnol1, diagnol2, board, res);
return res;
}
public void recSolveNQueens(int row, int n, boolean[] cols, boolean[] diagnol1, boolean[] diagnol2, String[] board, List<List<String>> res) {
if (row == n) {
res.add(convertToList(board));
return;
}
for (int col = 0; col < n; col++) {
int index1 = row + col;
int index2 = row - col + n;
if (cols[col] || diagnol1[index1] || diagnol2[index2]) {
continue;
}
char[] rowArr = new char[n];
Arrays.fill(rowArr, '.');
rowArr[col] = 'Q';
board[row] = new String(rowArr);
cols[col] = true;
diagnol1[index1] = true;
diagnol2[index2] = true;
recSolveNQueens(row + 1, n, cols, diagnol1, diagnol2, board, res);
diagnol2[index2] = false;
diagnol1[index1] = false;
cols[col] = false;
}
}
public List<String> convertToList(String[] board) {
List<String> res = new ArrayList();
for (String row : board) {
res.add(row);
}
return res;
}
}