-
Notifications
You must be signed in to change notification settings - Fork 5
/
n_queen_print_one.cpp
70 lines (61 loc) · 1.09 KB
/
n_queen_print_one.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
#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;
}
bool NQueen(int n, int board[][10], int i) {
//Base Case
if (i == n) {
//Print the board
for (int x = 0; x < n; x++) {
for (int y = 0; y < n; y++) {
cout << board[x][y] << " ";
}
cout << endl;
}
cout << endl;
return true;
}
//Rec Case
//Try to place queen at every column/position in the current row
for (int j = 0; j < n; j++) {
if (canPlace(board, n, i, j)) {
board[i][j] = 1;
bool aageQueenRakhPayeKya = NQueen(n, board, i + 1);
if (aageQueenRakhPayeKya) {
return true;
}
board[i][j] = 0;
}
}
return false;
}
int main() {
int board[10][10] = {0};
int n;
cin >> n;
cout << NQueen(n, board, 0);
return 0;
}