forked from anish2210/hacktober2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
N-QUEEN.c
75 lines (63 loc) · 1.86 KB
/
N-QUEEN.c
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
#include <iostream>
#include <vector>
using namespace std;
void printBoard(const vector<int>& board) {
int n = board.size();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (board[i] == j) {
cout << "Q ";
} else {
cout << ". ";
}
}
cout << endl;
}
cout << endl;
}
bool isSafe(const vector<int>& board, int row, int col) {
for (int i = 0; i < row; i++) {
if (board[i] == col || abs(board[i] - col) == abs(i - row)) {
return false;
}
}
return true;
}
// Function to solve the N-Queens problem using backtracking
void solveNQueens(vector<int>& board, int row, vector<vector<int>>& solutions) {
int n = board.size();
if (row == n) {
// Found a valid solution, add it to the list
solutions.push_back(board);
return;
}
for (int col = 0; col < n; col++) {
if (isSafe(board, row, col)) {
board[row] = col;
solveNQueens(board, row + 1, solutions);
board[row] = -1; // Backtrack
}
}
}
// Function to find all solutions to the N-Queens problem
vector<vector<int>> solveNQueens(int n) {
vector<int> board(n, -1); // Initialize the board with -1
vector<vector<int>> solutions;
solveNQueens(board, 0, solutions);
return solutions;
}
int main() {
int n;
cout << "Enter the number of queens (N): ";
cin >> n;
vector<vector<int>> solutions = solveNQueens(n);
if (solutions.empty()) {
cout << "No solutions found." << endl;
} else {
cout << "Found " << solutions.size() << " solution(s):" << endl;
for (const vector<int>& solution : solutions) {
printBoard(solution);
}
}
return 0;
}