-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathN-Queens_II.cpp
More file actions
30 lines (27 loc) · 830 Bytes
/
N-Queens_II.cpp
File metadata and controls
30 lines (27 loc) · 830 Bytes
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
class Solution {
public:
bool isPlace(int queen, int row, vector<int>& arr) {
for(int prev = 1; prev < queen; ++prev) {
if ( arr[prev] == row or abs(arr[prev] - row) == abs(prev - queen) )
return false;
}
return true;
}
int nQueen(int queen, int n, vector<int>& arr) {
if(queen > n) {
return 1;
}
int ret = 0;
for(int row = 1; row <= n; ++row) {
if(isPlace(queen, row, arr)) {
arr[queen] = row; // arr[i] = j means there is a queen in jth row and ith column
ret += nQueen(queen + 1, n, arr);
}
}
return ret;
}
int totalNQueens(int n) {
vector<int>arr(n + 1);
return nQueen(1, n, arr);
}
};