
Sponsored
Sponsored
This approach involves using backtracking to place queens row by row, exploring valid positions recursively. Each queen placement is validated based on column and diagonal restrictions. If a valid placement is found, the algorithm progresses to the next row, otherwise it backtracks and attempts alternative placements.
Time Complexity: O(N!), because we are trying N possible positions for each row for N queens.
Space Complexity: O(N^2), due to the storage of the board states and recursion stack.
1import java.util.*;
2
3public class NQueens {
4 private List<List<String>> solutions = new ArrayList<>();
5
6 public List<List<String>> solveNQueens(int n) {
7 char[][] board = new char[n][n];
8 for (int i = 0; i < n; i++) {
9 Arrays.fill(board[i], '.');
10 }
11 boolean[] cols = new boolean[n];
12 boolean[] d1 = new boolean[2 * n];
13 boolean[] d2 = new boolean[2 * n];
14 backtrack(board, 0, cols, d1, d2);
15 return solutions;
16 }
17
18 private void backtrack(char[][] board, int row, boolean[] cols, boolean[] d1, boolean[] d2) {
19 int n = board.length;
20 if (row == n) {
21 solutions.add(transform(board));
22 return;
23 }
24
25 for (int col = 0; col < n; col++) {
26 int id1 = col - row + n;
27 int id2 = col + row;
28 if (!cols[col] && !d1[id1] && !d2[id2]) {
29 board[row][col] = 'Q';
30 cols[col] = d1[id1] = d2[id2] = true;
31 backtrack(board, row + 1, cols, d1, d2);
32 board[row][col] = '.';
33 cols[col] = d1[id1] = d2[id2] = false;
34 }
35 }
36 }
37
38 private List<String> transform(char[][] board) {
39 List<String> ret = new ArrayList<>();
40 for (int i = 0; i < board.length; i++) {
41 ret.add(new String(board[i]));
42 }
43 return ret;
44 }
45
46 public static void main(String[] args) {
47 NQueens nQueens = new NQueens();
48 List<List<String>> solutions = nQueens.solveNQueens(4);
49 for (List<String> solution : solutions) {
50 for (String row : solution) {
51 System.out.println(row);
52 }
53 System.out.println();
54 }
55 }
56}This Java solution uses a recursive backtracking technique, similar to the C++ approach. The board is initialized and backtrack is used to attempt each queen placement. Transformations into string lists are performed before adding complete solutions to the results.
This approach optimizes the placement verification using bit manipulation, reducing the auxiliary space by managing columns and diagonals in integer bitmasks. This permits efficient bitwise operations for placing queens and checking potential attacks.
Time Complexity: O(N!), each row considers N placements, simplified by binary check.
Space Complexity: O(N), due to condensed state tracking via differential lists.
1import java.util.*;
2
3
This solution in Java embodies bit manipulation to track column and diagonal availability via bitmasks, ensuring low overhead while solving N-Queens recursively. Solutions are compiled as lists of strings to represent the board state efficiently.