N Queens

Eight queens puzzle

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
#include <iostream>
#include <vector>
#include <string>
using std::vector;
using std::string;
vector<bool> col;
vector<bool> diag;
vector<bool> antidiag;
void dfs(int i, int n, vector<vector<string> > &res, vector<string> &board) {
if (i == n) {
res.push_back(board);
return;
}
for (int j = 0; j < n; j++) {
if (!(col[j] && diag[i - j + n - 1] && antidiag[i + j])) {
continue;
}
board[i][j] = 'Q'; // Q stands for queen
col[j] = diag[i - j + n - 1] = antidiag[i + j] = false;
dfs(i + 1, n, res, board);
board[i][j] = '.';
col[j] = diag[i - j + n - 1] = antidiag[i + j] = true;
}
}
vector<vector<string> > solveNQueens(int n) {
vector<vector<string> > res;
col = vector<bool>(n, true);
diag = vector<bool>(2 * n - 1, true);
antidiag = vector<bool>(2 * n - 1, true);
vector<string> board(n, string(n, '.'));
dfs(0, n, res, board);
return res;
}
int main() {
int n;
std::cout << "Pls input n: " << std::endl;
std::cin >> n;
vector<vector<string> > res = solveNQueens(n);
for (int i = 0; i < res.size(); i++) {
for (int j = 0; j < res[0].size(); j++) {
std::cout << res[i][j] << std::endl;
}
std::cout << "==========" << std::endl;
}
return 0;
}