forked from Assassin1771/HACKTOBERFEST-2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NQueen.cpp
54 lines (52 loc) · 1.28 KB
/
NQueen.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
#include<iostream>
#include<cstring>
using namespace std;
void printboard(bool **board,int n){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<<board[i][j]<<" ";
}
cout<<endl;
}
}
bool ifSafe(bool **board,int n, int row,int col){
for(int i=0;i<col;i++){
if(board[row][i]) return false;
}
for(int i=row,j=col;i>=0 &&j>=0;i--,j--){
if(board[i][j]) return false;
}
for(int i=row,j=col;i<n && j>=0;i++,j--){
if(board[i][j]) return false;
}
return true;
}
bool solve(bool **board,int n,int col){
if(col==n) {
printboard(board,n);
return true;
}
bool res = false;
for(int i=0;i<n;i++){
if(ifSafe(board,n,i,col)){
board[i][col] = 1;
res = solve(board,n,col+1) || res;
board[i][col] = 0;
}
}
return res;
}
int main(){
int n;
cin>>n;
bool **board;
board = new bool*[n];
for(int i = 0; i <n; i++) board[i] = new bool[n];
memset(board,0,sizeof(board));
printboard(board,n);
// bool ans = solve(board,n,0);
// if(ans == 0) cout<<"Solution does not exist !"<<endl;
for(int i=0;i<n;i++) free(board[i]);
free(board);
return 0;
}