-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path8queens 2d
61 lines (57 loc) · 3.27 KB
/
8queens 2d
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
#include<iostream>
using namespace std;
int main() {
int q[8][8] = {};// Initialize the board to 0
int count = 0;
int Row = 0, Col = 0;// Start in the 1st row, 1st column
q[Row][Col] = 1; // Place the first queen on the upper left corner
nextCol:
Col++; // Move to the next column
if(Col==8){ // If you passed the last column
goto print; //goto print
}
Row = -1; // Otherwise start at the "TOP" of the column
nextRow:
Row++; // Move to the next row
if(Row == 8){ // If you have passed the end of the column
goto backtrack;
} //goto backtrack
for(int i=0;i<Col;i++){ //for each square to the left of the current square
if(q[Row][i] == 1) // If there is a queen in the same row (to the left), goto nextRow
goto nextRow;
}
for(int i=1;Row-i>=0&&Col-i>=0;i++) //for each square to the left of the current square
if(q[Row-i][Col-i]==1) //if there is a queen on that square
goto nextRow; //goto nextRow;
for(int i=1;(Row+i)<8&&Col-i>=0;i++) //for (int i = 1; ...; i++)
if(q[Row+i][Col-i]==1) //if there is a queen i spots above and left of the current square
goto nextRow;
q[Row][Col]= 1; //goto nextRow;
goto nextCol; //goto nextCol;
backtrack:
Col--; // Move to the previous column
if(Col == -1){
return (0);
}
//if (you have moved to the left of the chessboard)
//exit the program
Row=0;
while(q[Row][Col]!=1)
Row++; // Find the square in the column with a queen in it and set r to the row number of that s
q[Row][Col]=0; // Remove the queen from the current square
goto nextRow; //goto nextRow;
print:
static int numSolutions = 0;
cout << "Solution #" << ++numSolutions << ":\n";
for(int i=0;i<8;i++){
for(int j=0;j<8;j++){
if(q[i][j]==1)
cout<<"1";
else
cout<<"0";
}
cout<<endl;
} //Use a nested loop to print the chessboard
cout<<endl;
goto backtrack;
}