-
Notifications
You must be signed in to change notification settings - Fork 1
/
eightQueens.cpp
57 lines (47 loc) · 1.13 KB
/
eightQueens.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
#include <iostream>
#include <vector>
using namespace std;
class Solution{
public:
vector<vector<int> > placeQueens(int n) {
vector<vector<int> > res;
vector<int> pos(n, -1);
placeQueensDFS(pos, 0, res);
printBoard(res);
return res;
}
void placeQueensDFS(vector<int> &pos, int row, vector<vector<int>> &res )
{
int n = pos.size();
if (row == n) res.push_back(pos);
else {
for (int col = 0; col < n; ++ col ){
if (isValid(pos, row, col)) {
pos[row] = col;
placeQueensDFS(pos, row + 1, res);
pos[row] = -1;
}
}
}
}
bool isValid(vector<int> &pos, int row, int col) {
for(int i = 0; i < row; ++i) {
if (col == pos[i] || abs(row - i) == abs(col - pos[i])) {
return false;
}
}
return true;
}
void printBoard(const vector<vector<int>> board) {
vector<vector<int>>::const_iterator row;
vector<int>::const_iterator col;
for (row = board.begin(); row != board.end(); row++)
for(col = row -> begin(); col != row -> end(); col++)
cout << *col << "";
cout << endl;
}
};
int main() {
Solution sol;
sol.placeQueens(3);
}