Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
afnan47
GitHub Repository: afnan47/sem7
Path: blob/main/DAA/5_nQueens.cpp
418 views
1
#include<bits/stdc++.h>
2
using namespace std;
3
4
bool isSafe(int **arr, int x, int y, int n){
5
for(int row=0;row<x;row++){
6
if(arr[row][y]==1){
7
return false;
8
}
9
}
10
11
int row =x;
12
int col =y;
13
while(row>=0 && col>=0){
14
if(arr[row][col]==1){
15
return false;
16
}
17
row--;
18
col--;
19
}
20
21
row =x;
22
col =y;
23
while(row>=0 && col<n){
24
if(arr[row][col]==1){
25
return false;
26
}
27
row--;
28
col++;
29
}
30
31
return true;
32
}
33
34
void printBoard(int **arr, int n){
35
for(int i=0;i<n;i++){
36
for(int j=0;j<n;j++){
37
if(arr[i][j] == 1) cout << "[Q]";
38
else cout << "[]";
39
}
40
cout << endl;
41
}
42
cout << endl;
43
cout << endl;
44
}
45
46
47
void nQueen(int** arr, int x, int n){
48
if(x == n){
49
printBoard(arr, n);
50
return;
51
}
52
53
for(int col=0;col<n;col++){
54
if(isSafe(arr,x,col,n)){
55
arr[x][col]=1;
56
nQueen(arr,x+1,n);
57
arr[x][col]=0;
58
}
59
}
60
}
61
62
63
int main(){
64
int n;
65
cin >> n;
66
67
int **arr = new int*[n];
68
for(int i=0;i<n;i++){
69
arr[i] = new int[n];
70
for(int j=0;j<n;j++){
71
arr[i][j]=0;
72
}
73
}
74
75
nQueen(arr, 0, n);
76
77
cout << "--------All possible solutions--------";
78
79
return 0;
80
}
81
82
/*
83
Time Complexity: O(N!)
84
Auxiliary Space: O(N^2)
85
*/
86