
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.
1#include <vector>
2#include <unordered_set>
3
4class Solution {
5public:
6 int totalNQueens(int n) {
7 std::unordered_set<int> columns, diag1, diag2;
8 return backtrack(0, n, columns, diag1, diag2);
9 }
10
11private:
12 int backtrack(int row, int n, std::unordered_set<int>& columns, std::unordered_set<int>& diag1, std::unordered_set<int>& diag2) {
13 if (row == n) return 1;
14 int count = 0;
15 for (int col = 0; col < n; ++col) {
16 if (columns.count(col) || diag1.count(row + col) || diag2.count(row - col)) continue;
17
18 columns.insert(col);
19 diag1.insert(row + col);
20 diag2.insert(row - col);
21
22 count += backtrack(row + 1, n, columns, diag1, diag2);
23
24 columns.erase(col);
25 diag1.erase(row + col);
26 diag2.erase(row - col);
27 }
28 return count;
29 }
30};The C++ solution utilizes `std::unordered_set` for columns and diagonals to check the safety of placing the queens. Through recursive backtracking, it explores each row, placing a queen only if no set has the conflicting column or diagonal.
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
JavaScript benefits from using bitmasking to handle calculations for columns and diagonals, significantly boosting performance when transitioning through potential queen placements.