
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.
1using System.Collections.Generic;
2
3public class Solution {
4 public int TotalNQueens(int n) {
5 var cols = new HashSet<int>();
6 var diag1 = new HashSet<int>();
7 var diag2 = new HashSet<int>();
8 return Backtrack(0, n, cols, diag1, diag2);
9 }
10
11 private int Backtrack(int row, int n, HashSet<int> cols, HashSet<int> diag1, HashSet<int> 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 C# implementation leverages HashSets to track unsafe columns and diagonals for queen placement. It utilizes a backtracking method that places queens row by row, updating constraints accordingly.
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.