-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy path51.cpp
75 lines (64 loc) · 1.93 KB
/
51.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
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
using namespace std;
class Solution {
public:
bool isValid(vector<int> &columns, int row) {
for (int i = 0; i < row; i++) {
if (columns[i] == columns[row]
|| abs(columns[i] - columns[row]) == (row - i)) {
return false;
}
}
return true;
}
void placeQueens(vector<vector<string> > &ret, vector<int> &columns, int row) {
int n = columns.size();
if (row == n) { /* found one solution! */
vector<string> solution;
/* build solution vector */
for (int i = 0; i < n; i++) {
string line(n, '.');
line[columns[i]] = 'Q';
solution.push_back(line);
}
ret.push_back(solution);
return;
}
for (int j = 0; j < n; j++) {
/* try to place a queen in this row */
columns[row] = j;
/* put another queen in next row if this row's position is valid */
if (isValid(columns, row)) {
placeQueens(ret, columns, row + 1);
}
}
}
vector<vector<string> > solveNQueens(int n) {
vector<vector<string> > ret;
vector<int> columns(n, 0);
placeQueens(ret, columns, 0);
return ret;
}
};
int main() {
Solution s;
vector<vector<string> > ret;
ret = s.solveNQueens(4);
for (int i = 0; i < ret.size(); i++) {
for (int j = 0; j < ret[0].size(); j++) {
cout << ret[i][j] << endl;
}
cout << "----" << endl;
}
ret = s.solveNQueens(5);
for (int i = 0; i < ret.size(); i++) {
for (int j = 0; j < ret[0].size(); j++) {
cout << ret[i][j] << endl;
}
cout << "-----" << endl;
}
return 0;
}