
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 public int TotalNQueens(int n) {
return Solve(n, 0, 0, 0, 0);
}
private int Solve(int n, int row, int columns, int diag1, int diag2) {
if (row == n) return 1;
int count = 0;
for (int col = 0; col < n; col++) {
int colMask = 1 << col;
if ((columns & colMask) == 0 && (diag1 & (1 << (row + col))) == 0 && (diag2 & (1 << (row - col + n - 1))) == 0) {
count += Solve(n, row + 1, columns | colMask, diag1 | (1 << (row + col)), diag2 | (1 << (row - col + n - 1)));
}
}
return count;
}
}This C# version employs bitwise operations similarly, adeptly balancing checks on column and diagonal occupation with quick updates achieved through bit shifts.