
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.
1var totalNQueens = function(n) {
2 let cols = new Set();
3 let diag1 = new Set();
4 let diag2 = new Set();
5
6 const backtrack = (row) => {
7 if (row === n) return 1;
8 let count = 0;
9 for (let col = 0; col < n; col++) {
10 if (cols.has(col) || diag1.has(row + col) || diag2.has(row - col)) continue;
11 cols.add(col);
12 diag1.add(row + col);
13 diag2.add(row - col);
14 count += backtrack(row + 1);
15 cols.delete(col);
16 diag1.delete(row + col);
17 diag2.delete(row - col);
18 }
19 return count;
20 };
21
22 return backtrack(0);
23};In JavaScript, we use Set objects to track column and diagonal attacks. The core is a recursive `backtrack` function that tries placing a queen at each row and validates against occupied positions via the sets.
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 C implementation utilizes bitmasking for columns and diagonals, enabling efficient checking and updating of states. The code iterates over possible columns, shifting bit positions to represent occupation and recursively exploring valid paths.