-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathnQueen_Code.cpp
More file actions
81 lines (70 loc) · 1.53 KB
/
nQueen_Code.cpp
File metadata and controls
81 lines (70 loc) · 1.53 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
80
81
// here is the code for the n-queen pattern of nXn board.
#include <iostream>
using namespace std;
bool canPlace(int board[][20],int n,int x,int y){
//Column
for(int k=0;k<x;k++){
if(board[k][y]==1){
return false;
}
}
//Left Diag
int i = x;
int j = y;
while(i>=0 and j>=0){
if(board[i][j]==1){
return false;
}
i--; j--;
}
//Right Diag
i = x;
j = y;
while(i>=0 and j<n){
if(board[i][j]==1){
return false;
}
i--; j++;
}
return true;
}
void printBoard(int n,int board[][20]){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<< board[i][j]<<" ";
}
cout<<endl;
}
cout <<endl;
}
bool solveNQueen(int n,int board[][20],int i){
//base case
if(i==n){
//Print the board
printBoard(n,board);
return true;
}
// rec case
// try to place a queen in every row
for(int j=0;j<n;j++){
//whether the current i,j is safe or not
if(canPlace(board,n,i,j)){
board[i][j] = 1;
bool success = solveNQueen(n,board,i+1);
if(success){
return true;
}
//backtrack
board[i][j] = 0;
}
}
return false;
}
int main() {
system("CLS");
int board[20][20] = {0};
int n;
cin>>n;
solveNQueen(n,board,0);
return 0;
}