the idea is do dfs from the first row to the last row, put in col one by one, and validate the correctness.
so we only need to check top above(top-left, top, top-right ), if there are Queen, return false
top: loop row from 0 to current row -1
top-left : like (. row - k, col -k), k start from 1
top-right: (row - k, col + k) k start from 1
T: O(n^n), but a lot of pruning, so it's fast
S: O(n^2)
class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> res = new ArrayList<>();
char[][] board = new char[n][n];
for (int i = 0; i < n; i++) {
Arrays.fill(board[i], '.');
}
dfs(0, board, res);
return res;
}
private void dfs(int row, char[][] board, List<List<String>> res) {
int n = board.length;
if (row == n) {
addToResult(board, res);
return;
}
// try this row, each col data
for (int col = 0; col < n; col++) {
if (isValid(board, row, col)) {
board[row][col] = 'Q';
dfs(row+1, board, res); // drill down to next row
board[row][col] = '.';
}
}
}
private void addToResult(char[][] board, List<List<String>> res) {
List<String> list = new ArrayList<>();
for (int i = 0; i < board.length; i++) {
list.add(String.valueOf(board[i]));
}
res.add(list);
}
private boolean isValid(char[][] board, int row, int col) {
// check top (0~row, same col)
for (int i = 0; i < row; i++) { // entire col
if (board[i][col] == 'Q') {
return false;
}
}
// this don't need check, we just check above this (row, col)'s data
//for (int j = 0; j < col; j++) { // entire row
// if (board[row][j] == 'Q') {
// return false;
// }
//}
int k = 1; // 左上角, top-left
while (row - k >= 0 && col - k >= 0) {
if (board[row - k][col - k] == 'Q') {
return false;
}
k++;
}
k = 1; // 右上角, top-right
while (row - k >= 0 && col + k < board.length) {
if (board[row - k][col + k] == 'Q') {
return false;
}
k++;
}
return true;
}
}