forked from Anchor89/LeetCodeAnchor89
-
Notifications
You must be signed in to change notification settings - Fork 0
/
N-QueensII.cpp
30 lines (29 loc) · 833 Bytes
/
N-QueensII.cpp
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
#include "LeetCode.h"
class Solution {
public:
int result;
vector<vector<bool>> board;
vector<bool> col, diag, rdiag;
void solve(vector<vector<bool>>& board, int line) {
if (line == board.size()) {
result++;
return;
}
int n = board.size();
for (int i=0; i<n; i++) {
if (col[i] || diag[i+line] || rdiag[line-i+n-1]) continue;
board[line][i] = col[i] = diag[i+line] = rdiag[line-i+n-1] = true;
solve(board, line+1);
board[line][i] = col[i] = diag[i+line] = rdiag[line-i+n-1] = false;
}
}
int totalNQueens(int n) {
result = 0;
board.clear(); board.resize(n, vector<bool>(n, false));
col.clear(); col.resize(n, false);
diag.clear(); diag.resize(n<<1, false);
rdiag.clear(); rdiag.resize(n<<1, false);
solve(board, 0);
return result;
}
};