-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathN-Queen.cpp
More file actions
79 lines (62 loc) · 1.12 KB
/
Copy pathN-Queen.cpp
File metadata and controls
79 lines (62 loc) · 1.12 KB
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
76
77
78
79
#include<bits/stdc++.h>
using namespace std;
bool check(int** a,int x,int y,int n){
for(int r=0;r<x;r++){
if(a[r][y]==1){
return false;
}
}
int r=x;
int c=y;
while(r>=0 && c>=0){
if(a[r][c]==1){
return false;
}
r--;
c--;
}
r=x;
c=y;
while(r>=0 && c<n-1){
if(a[r][c]==1){
return false;
}
r--;
c++;
}
return true;
}
bool nQueen(int** a,int x,int n){
if(x>=n){
return true;
}
for(int c=0;c<n;c++){
if(check(a,x,c,n)){
a[x][c]==1;
if(nQueen(a,x+1,n)){
return true;
}
a[x][c]=0; //Backtrack
}
}
return false;
}
int main(){
int n;
cin>>n;
int** a=new int*[n];
for(int i=0;i<n;i++){
a[i]=new int[n];
for(int j=0;j<n;j++){
a[i][j]=0;
}
}
if(nQueen(a,0,n)){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<<a[i][j]<<" ";
}
cout<<endl;
}
}
}