-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.cpp
More file actions
83 lines (69 loc) · 1.98 KB
/
Copy pathsolution.cpp
File metadata and controls
83 lines (69 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/**
* Problem: 52. N-Queens II
* Difficulty: Hard
* Topics: Backtracking, Bit Manipulation
* LeetCode Link: https://leetcode.com/problems/n-queens-ii/
*
* Time Complexity: O(N!)
* Space Complexity: O(N) recursion stack space
*/
#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
class Solution {
private:
int totalCount = 0;
void backtrack(int row, int n, int cols, int diag1, int diag2) {
if (row == n) {
totalCount++;
return;
}
// Available safe positions for current row
int available = ((1 << n) - 1) & ~(cols | diag1 | diag2);
while (available > 0) {
int p = available & -available; // Isolate least significant bit
available -= p;
// In next row:
// diag1 shifts left (<< 1) because row increases by 1
// diag2 shifts right (>> 1) because row increases by 1
backtrack(row + 1, n, cols | p, (diag1 | p) << 1, (diag2 | p) >> 1);
}
}
public:
int totalNQueens(int n) {
totalCount = 0;
backtrack(0, n, 0, 0, 0);
return totalCount;
}
};
// ==========================================
// Local Test Runner (Guarded for LeetCode Submission)
// ==========================================
#ifdef LOCAL_TEST
int main() {
Solution solver;
// Test Case 1: n = 4 -> 2
{
assert(solver.totalNQueens(4) == 2);
cout << "Test 1 Passed: n = 4 -> 2" << endl;
}
// Test Case 2: n = 1 -> 1
{
assert(solver.totalNQueens(1) == 1);
cout << "Test 2 Passed: n = 1 -> 1" << endl;
}
// Test Case 3: n = 8 -> 92
{
assert(solver.totalNQueens(8) == 92);
cout << "Test 3 Passed: n = 8 -> 92" << endl;
}
// Test Case 4: n = 9 -> 352
{
assert(solver.totalNQueens(9) == 352);
cout << "Test 4 Passed: n = 9 -> 352" << endl;
}
cout << "All test cases passed successfully!" << endl;
return 0;
}
#endif