
Sponsored
Sponsored
This approach involves using backtracking to explore all possible ways of placing queens on the board. We maintain three sets to keep track of which columns and diagonals are already occupied by queens, ensuring no two queens threaten each other.
Time Complexity: O(n!), where n is the number of queens. Each queen has n options initially, and it decreases with increasing constraints.
Space Complexity: O(n) for the call stack and additional space for tracking columns and diagonals.
1import java.util.HashSet;
2
3public class Solution {
4 public int totalNQueens(int n) {
5 HashSet<Integer> cols = new HashSet<>();
6 HashSet<Integer> diag1 = new HashSet<>();
7 HashSet<Integer> diag2 = new HashSet<>();
8 return backtrack(0, n, cols, diag1, diag2);
9 }
10
11 private int backtrack(int row, int n, HashSet<Integer> cols, HashSet<Integer> diag1, HashSet<Integer> diag2) {
12 if (row == n) return 1;
13 int count = 0;
14 for (int col = 0; col < n; col++) {
15 if (cols.contains(col) || diag1.contains(row + col) || diag2.contains(row - col)) continue;
16 cols.add(col);
17 diag1.add(row + col);
18 diag2.add(row - col);
19 count += backtrack(row + 1, n, cols, diag1, diag2);
20 cols.remove(col);
21 diag1.remove(row + col);
22 diag2.remove(row - col);
23 }
24 return count;
25 }
26}This Java solution adopts the HashSet to store columns and both diagonal indexes, ensuring no two queens can attack each other. The recursive backtracking adds and removes these indexes while attempting to place queens row by row.
This approach leverages bitmasking to store state information about occupied columns and diagonals. By using integer variables as bit masks, we can efficiently check and update occupation states, which is particularly useful for handling small fixed-size constraints like n <= 9.
Time Complexity: O(n!). Recursive full exploration, though bitwise operations are computationally efficient.
Space Complexity: O(n) due to recursion depth and bitmask integers.
1
The Python method focuses on bitwise operations to manage placements, making column and diagonal checks very fast. Even across a relatively small n=9 board, bit manipulations provide a clear advantage in processing speed.