-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path8 Queens 1 Dimensional.cpp
72 lines (52 loc) · 1.18 KB
/
8 Queens 1 Dimensional.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include<iostream>
using namespace std;
bool ok(int q[], int column){
for(int i=0; i<column; i++){
if((q[i] == q[column]) || (abs(q[column] - q[i]) == (column - i)))
return false;
}
return true;
}
void Backtrack(int &column){
column--;
if(column==-1) exit(1);
}
void Print(int q[]){
static int counter = 0;
counter++;
int board[8][8]={0};
cout<<"Solution #"<<counter<<endl;
for(int i=0; i<8; i++){
board[q[i]][i]=1;
}
for(int i=0;i<8;i++){
for(int j=0;j<8;j++)
cout<<board[i][j]<<" ";
cout<<endl;
}
cout << endl;
}
int main(){
int q[8]; q[0]=0;
int c=1;
bool _backtrack=false;
while(1){
while(c<8){
if(!_backtrack)
q[c]=-1;
_backtrack=false;
while(q[c]<8){
q[c]++;
while(q[c]==8){
Backtrack(c);
q[c]++;}
if(ok(q, c))
break;
}
c++;
}
Print(q);
Backtrack(c);
_backtrack=true;
}
}