-
Notifications
You must be signed in to change notification settings - Fork 0
/
n-queens.cpp
55 lines (52 loc) · 1.1 KB
/
n-queens.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
#include<bits/stdc++.h>
#define int int64_t
using namespace std;
void printBoard(int n,int board[20][20]){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++) cout<<board[i][j]<<" ";
cout<<endl;
}
cout<<endl;
}
bool canPlace(int n,int board[20][20],int x,int y){
int i = x, j = y;
while(i>=0){
if(board[i][j]==1) return false;
i--;
}
i=x,j=y;
while(i>=0 && j>=0){
if(board[i][j]==1) return false;
i--;j--;
}
i=x,j=y;
while(i>=0 && j<n){
if(board[i][j]==1) return false;
i--;j++;
}
return true;
}
bool solve(int n,int board[20][20],int i){
if(i==n){
printBoard(n,board);
return true;
}
for(int j=0;j<n;j++){
if(canPlace(n,board,i,j)){
board[i][j]=1;
bool success = solve(n,board,i+1);
//if(success) return true;
board[i][j]=0;
}
}
return false;
}
int32_t main(){
freopen("cp.in", "r", stdin);
freopen("cp.out", "w", stdout);
int board[20][20] = {0};
int n ;
cin>>n;
solve(n,board,0);
return 0;
}