forked from MAYANK25402/Hactober-2023-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
N_QUEEN.cpp
62 lines (57 loc) · 1.41 KB
/
N_QUEEN.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>
#include <vector>
using namespace std;
bool is_attack(int i, int j, vector<vector<int>> &board, int n) {
for (int k = 0; k < n; k++) {
if (board[i][k] == 1 || board[k][j] == 1) {
return true;
}
}
for (int k = 0; k < n; k++) {
for (int l = 0; l < n; l++) {
if ((k + l == i + j) || (k - l == i - j)) {
if (board[k][l] == 1) {
return true;
}
}
}
}
return false;
}
bool n_queen_helper(vector<vector<int>> &board, int col, int n) {
if (col >= n) {
return true;
}
for (int i = 0; i < n; i++) {
if (!is_attack(i, col, board, n)) {
board[i][col] = 1;
if (n_queen_helper(board, col + 1, n)) {
return true;
}
board[i][col] = 0;
}
}
return false;
}
void print_board(vector<vector<int>> &board) {
for (int i = 0; i < board.size(); i++) {
for (int j = 0; j < board.size(); j++) {
cout << board[i][j] << " ";
}
cout << endl;
}
}
void n_queen(int n) {
vector<vector<int>> board(n, vector<int>(n, 0));
if (!n_queen_helper(board, 0, n)) {
cout << "Solution does not exist" << endl;
return;
}
print_board(board);
}
int main() {
int n;
cout << "Enter the value of N: ";
cin >> n;
n_queen(n);
}