N-Queens
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.."] ]
Time complexity: O(n!)
Note: this solution is left the room for improvement.
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>> result = new ArrayList<>();
helperNQueens(board, 0, result);
return result;
}
private void helperNQueens(char[][] board, int row, List<List<String>> result) {
if (row == board.length) {
List<String> current = new ArrayList();
for (int i = 0; i < board.length; i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < board[0].length; j++) {
sb.append(board[i][j]);
}
current.add(sb.toString());
}
result.add(current);
} else {
// check each cells in column
for (int j = 0; j < board[0].length; j++) {
if (isSafe(board, row, j)) {
board[row][j] = 'Q';
helperNQueens(board, row + 1, result);
board[row][j] = '.';
}
}
}
}
private boolean isSafe(char[][] board, int m, int n) {
// check all rows above
for (int i = 0; i < m; i++) {
if (board[i][n] == 'Q')
return false;
}
// check left diagonal
int i = m -1;
int j = n - 1;
while (i >= 0 && j >= 0) {
if (board[i][j] == 'Q') {
return false;
}
i--;
j--;
}
// check right diagonal
i = m -1;
j = n + 1;
while (i >= 0 && j < board[0].length) {
if (board[i][j] == 'Q') {
return false;
}
i--;
j++;
}
return true;
}