forked from MAYANK25402/Hactober-2023-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNQueens.cpp
67 lines (58 loc) · 1.72 KB
/
NQueens.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
#include <iostream>
#include <vector>
class NQueens {
public:
static void display(const std::vector<std::vector<bool>>& board) {
for (const auto& row : board) {
for (bool element : row) {
if (element) {
std::cout << "Q ";
} else {
std::cout << "X ";
}
}
std::cout << std::endl;
}
}
static bool isSafe(const std::vector<std::vector<bool>>& board, int row, int col) {
for (int i = 0; i < row; i++) {
if (board[i][col]) {
return false;
}
}
int maxLeft = std::min(row, col);
for (int i = 1; i <= maxLeft; i++) {
if (board[row - i][col - i]) {
return false;
}
}
int maxRight = std::min(row, static_cast<int>(board.size()) - col - 1);
for (int i = 1; i <= maxRight; i++) {
if (board[row - i][col + i]) {
return false;
}
}
return true;
}
static int queens(std::vector<std::vector<bool>>& board, int row) {
if (row == board.size()) {
display(board);
std::cout << std::endl;
return 1;
}
int count = 0;
for (int col = 0; col < board.size(); col++) {
if (isSafe(board, row, col)) {
board[row][col] = true;
count += queens(board, row + 1);
board[row][col] = false;
}
}
return count;
}
};
int main() {
std::vector<std::vector<bool>> board(4, std::vector<bool>(4, false));
std::cout << NQueens::queens(board, 0) << std::endl;
return 0;
}