-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathn_queen.cpp
More file actions
38 lines (36 loc) · 744 Bytes
/
n_queen.cpp
File metadata and controls
38 lines (36 loc) · 744 Bytes
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
#include <iostream>
#include <cmath>
using namespace std;
int board[20], n;
bool isSafe(int row, int col) {
for (int prev = 1; prev < row; prev++) {
if (board[prev] == col || abs(board[prev] - col) == abs(prev - row))
return false;
}
return true;
}
void printSolution() {
cout << "[ ";
for (int i = 1; i <= n; i++) {
cout << board[i] << " ";
}
cout << "]" << endl;
}
void solve(int row) {
if (row > n) {
printSolution();
return;
}
for (int col = 1; col <= n; col++) {
if (isSafe(row, col)) {
board[row] = col;
solve(row + 1);
}
}
}
int main() {
cout << "Enter N: ";
cin >> n;
solve(1);
return 0;
}