-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNQueenProblem.cpp
More file actions
72 lines (68 loc) · 1.44 KB
/
NQueenProblem.cpp
File metadata and controls
72 lines (68 loc) · 1.44 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
#include <iostream>
using namespace std;
void printBoard(int board[][20], int n){
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 board[][20], int n, int x, int y){
//column
for(int k=0;k<= x;k++){
if(board[k][y] == 1){
return false;
}
}
//left diagonal
int i=x, j=y;
while(i>= 0 && j>= 0){
if(board[i][j] == 1){
return false;
}
i--;
j--;
}
//right diagonal
i=x, j=y;
while(i>= 0 && j>= 0){
if(board[i][j] == 1){
return false;
}
i--;
j++;
}
return true;
}
bool solveNQueen(int board[][20], int n, int i){
//base case
if(i == n){
printBoard(board, n);
return true;
}
//rec case
//trying to place a queen in every row
for(int j=0;j<n;j++){
//checking if the current i,j is safe of not
if(canPlace(board, n,i,j)){
board[i][j] = 1;
bool success = solveNQueen(board, n, i+1);
if(success){
return true;
}
//backtracking step
board[i][j]= 0;
}
}
return false;
}
int main()
{
int n;
cin>>n;
int board[20][20]= {0};
solveNQueen(board, n, 0);
return 0;
}