-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathN-QueensII.cpp
More file actions
74 lines (65 loc) · 1.62 KB
/
N-QueensII.cpp
File metadata and controls
74 lines (65 loc) · 1.62 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
#include <bits/stdc++.h>
using namespace std;
class Solution {
private:
int count = 0;
vector<string> board;
bool isValidVertical(int row, int col) {
while (row >= 0) {
if (board[row][col] == 'Q') {
return false;
}
row--;
}
return true;
}
bool isValidDiagonal(int row, int col) {
int i = row, j = col;
while (i >= 0 && j < board.size()) {
if (board[i][j] == 'Q') {
return false;
}
i--;
j++;
}
i = row, j = col;
while (i >= 0 && j >= 0) {
if (board[i][j] == 'Q') {
return false;
}
i--;
j--;
}
return true;
}
bool isValid(int row, int col) {
return isValidVertical(row, col) && isValidDiagonal(row, col);
}
public:
void solve(int row, int n) {
if (row == n) {
count++;
return;
}
for (int i = 0; i < n; i++) {
if (isValid(row, i)) {
board[row][i] = 'Q';
solve(row + 1, n);
board[row][i] = '.';
}
}
}
int totalNQueens(int n) {
string str = "";
for (int i = 0; i < n; i++) str.push_back('.');
for (int i = 0; i < n; i++) board.push_back(str);
solve(0, n);
return count;
}
};
int main() {
int n;
cin >> n;
int out = (new Solution())->totalNQueens(n);
cout << out << endl;
}