-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtry_queen.cpp
More file actions
47 lines (42 loc) · 762 Bytes
/
Copy pathtry_queen.cpp
File metadata and controls
47 lines (42 loc) · 762 Bytes
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
/* n queen problem using Backtracking */
#include<iostream>
#include<math.h>
using namespace std;
int board[100]={0};
int n;
int canPlace(int row, int col){
for (int i=0; i<row; i++){
if (board[i]==col)
return 0;
if (abs(col-board[i])==abs(row-i))
return 0;
}
return 1;
}
void nqueen(int row){
for (int col=0; col<n; col++){
if (canPlace(row, col)){
board[row]=col;
if (row==n-1){
cout<<"\n\n";
for (int i=0; i<n; i++){
for (int j=0; j<n; j++){
if (board[i]==j)
cout<<"\t1";
else
cout<<"\t0";
}
cout<<endl;
}
}
else
nqueen(row+1);
}
}
}
int main(){
cout<<"Enter the number of queens: ";
cin>>n;
nqueen(0);
return 0;
}