-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathn_queens.cpp
More file actions
98 lines (87 loc) · 1.93 KB
/
Copy pathn_queens.cpp
File metadata and controls
98 lines (87 loc) · 1.93 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool is_safe(vector<vector<int> > board, int row, int column, int n) {
int t_r = row, t_c = column;
// check row at the left
while (t_c >= 0) {
if (board[row][t_c] == 1) return false;
--t_c;
}
// check row at the right
t_c = column;
while (t_c < n) {
if (board[row][t_c] == 1) return false;
++t_c;
}
// check column a the top
while (t_r >= 0) {
if (board[t_r][row] == 1) return false;
--t_r;
}
t_r = row;
// check column at the bottom
while(t_r < n) {
if (board[t_r][row] == 1) return false;
++t_r;
}
// check top left diagonal
t_r = row, t_c = column;
while (t_c >= 0 && t_r >= 0) {
if (board[t_r][t_c] == 1) return false;
--t_c;
--t_r;
}
// check top right diagonal
t_r = row, t_c = column;
while (t_c >= 0 && t_r < n) {
if (board[t_r][t_c] == 1) return false;
--t_c;
++t_r;
}
return true;
// // check bottom right diagonal
// t_r = row, t_c = column;
// while (t_c < n && t_r < n) {
// if (board[t_c][t_r] == 1) return false;
// ++t_c;
// ++t_r;
// }
// // check bottom left diagonal
// t_r = row, t_c = column;
// while (t_c < n && t_r >= 0) {
// if (board[t_c][t_r] == 1) return false;
// ++t_c;
// --t_r;
// }
}
vector<vector<int> > foo(vector<vector<int> > board, int row, int n) {
// if came to the last row - solution is found
if (row == n) {
return board;
}
// start at the row
for (int i = row; i < n; ++i) {
// loop over each column and try to place a queen
for (int j = 0; j < n; ++j) {
if (is_safe(board, j, i, n)) {
board[i][j] = 1;
foo(board, row + 1, n);
}
}
}
}
int main() {
int n;
cin >> n;
vector<vector<int> > board(n, vector<int>(n, 0));
vector<vector<int> > result = foo(board, 0, board.size());
for (int i = 0; i < result.size(); ++i) {
for (int j = 0; j < result.size(); ++j) {
cout << result[i][j] << " ";
}
cout << endl;
}
return 0;
}