-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathnqueen_brute.cpp
62 lines (52 loc) · 914 Bytes
/
nqueen_brute.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
#include<iostream>
using namespace std;
bool canPlace(int board[][10], int n, int x, int y) {
//Column
for (int k = 0; k < x; k++) {
if (board[k][y] == 1) {
return false;
}
}
//Left Diag
int i = x, j = y;
while (i >= 0 and j >= 0) {
if (board[i][j] == 1) {
return false;
}
i--; j--;
}
//Right Diag
i = x, j = y;
while (i >= 0 and j < n) {
if (board[i][j] == 1) {
return false;
}
i--; j++;
}
return true;
}
int NQueen(int n, int board[][10], int i) {
//Base Case
if (i == n) {
//Print the board
return 1;
}
//Rec Case
//Try to place queen at every column/position in the current row
int cnt = 0;
for (int j = 0; j < n; j++) {
if (canPlace(board, n, i, j)) {
board[i][j] = 1;
cnt += NQueen(n, board, i + 1);
board[i][j] = 0;
}
}
return cnt;
}
int main() {
int board[10][10] = {0};
int n;
cin >> n;
cout << NQueen(n, board, 0);
return 0;
}