-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathNQueenProblem.cpp
More file actions
67 lines (58 loc) · 1.17 KB
/
NQueenProblem.cpp
File metadata and controls
67 lines (58 loc) · 1.17 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
#include <iostream>
using namespace std;
bool isSafe(int r, int c, int board[][10],int n){
//vertical check
for(int i=0;i<r;i++){
if(board[i][c]==1){
return false;
}
}
// upper left-diagonal
int i = r;
int j = c;
while(i>=0 && j>=0){
if(board[i][j]==1){
return false;
}
i--;
j--;
}
//upper right-diagonal
i = r;
j = c;
while(i>=0 && j<n){
if(board[i][j]==1){
return false;
}
i--;
j++;
}
return true;
}
void placeNQueens(int n, int i, int board[][10]){
if( i == n){
//print board
for(int k = 0; k < n; k++){
for(int l = 0; l < n; l++){
cout << board[k][l] <<" ";
}
// cout<<endl;
}
cout<<endl;
return;
}
for(int j = 0; j < n ; j++) {
if(isSafe(i,j,board,n)){
board[i][j] = 1;
placeNQueens(n,i+1,board);
board[i][j]=0;
}
}
}
void placeNQueens(int n){
int board[10][10] = {};
placeNQueens(n,0,board);
}
int main() {
placeNQueens(4);
}