The n-queens puzzle is the problem of placing n queens on an n x 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.
Example
Example 1:
1 2 3
Input: n = 4 Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]] Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above
classSolution{ privatevoidsolve(char[][] curr, int idx, int n, List<List<String>> ret, boolean[] col, boolean[] diag1, boolean[] diag2){ if (idx == n) { List<String> toAdd = new ArrayList<>(); for (int i = 0; i < n; i ++) { toAdd.add(String.valueOf(curr[i])); } ret.add(toAdd); return; }
for (int j = 0; j < n; j ++) { if (col[j] || diag1[idx + n - j - 1] || diag2[idx + j]) { continue; } col[j] = true; diag1[idx + n - j - 1] = true; diag2[idx + j] = true; curr[idx][j] = 'Q'; solve(curr, idx + 1, n, ret, col, diag1, diag2); curr[idx][j] = '.'; col[j] = false; diag1[idx + n - j - 1] = false; diag2[idx + j] = false; } } public List<List<String>> solveNQueens(int n) { List<List<String>> ret = new ArrayList<>(); char[][] curr = newchar[n][n]; for (int i = 0; i < n; i ++) { for (int j = 0; j < n; j ++) { curr[i][j] = '.'; } } boolean[] col = newboolean[n]; boolean[] diag1 = newboolean[2 * n - 1]; boolean[] diag2 = newboolean[2 * n - 1]; solve(curr, 0, n, ret, col, diag1, diag2); return ret; } }