-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathn_queens.cpp
81 lines (63 loc) · 1.81 KB
/
n_queens.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
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
#include <iostream>
#include <set>
#include <vector>
#include <string>
#include <numeric>
#include <algorithm>
#include <functional>
using std::set;
using std::vector;
using std::string;
struct DataStore{
set<int>& col;
set<int>& positiveDiag; // r + c
set<int>& negativeDiag; // r - c
vector<vector<string>>& result;
vector<vector<string>>& board;
int& n;
};
void backtrack (DataStore& store, int r){
auto [col, positiveDiag, negativeDiag, result, board, n] = store;
if (r == n){
vector<string> validBoard{};
for (vector<string>& row : board){
string sRow = std::accumulate(row.begin(), row.end(), string(), [](string accum, string curCol){
return std::move(accum) + curCol;
});
validBoard.push_back(sRow);
}
result.push_back(validBoard);
return;
}
for (int c =0; c < n ; c++){
if (col.find(c) != col.end() || positiveDiag.find(r+c) != positiveDiag.end() || negativeDiag.find(r-c) != negativeDiag.end())
continue;
col.insert(c);
positiveDiag.insert(r+c);
negativeDiag.insert(r-c);
board[r][c] = "Q";
backtrack(store, r+1);
col.erase(c);
positiveDiag.erase(r+c);
negativeDiag.erase(r-c);
board[r][c] = ".";
}
}
std::vector<std::vector<std::string>> solveNQueens(int n){
set<int> col{};
set<int> positiveDiag{}; // r + c
set<int> negativeDiag{}; // r - c
vector<vector<string>> result{};
vector<vector<string>> board (n, vector<string>(n, "."));
DataStore store{col, positiveDiag, negativeDiag, result, board , n};
backtrack(store, 0);
return result;
}
int main(){
auto result{solveNQueens(8)};
for (auto& validSol : result){
for_each(validSol.begin(), validSol.end(),[] (string& input){std::cout << input<<std::endl;});
std::cout <<std::endl<<std::endl;
}
return 0;
}