Question: Can someone explain how this code works? It's a one dimensional array that solves the 8 Queens problem. Each column number says which row number
Can someone explain how this code works? It's a one dimensional array that solves the 8 Queens problem. Each column number says which row number the Queen will be in.
#include
using namespace std;
int main() {
int b[8]={0};
int r = 0;
int c = 0;
nextCol: c++;
if (c > 7)
goto print;
r = -1;
nextRow: r++;
b[c] = r;
if(r > 7)
goto backtrack;
for(int i = 1; i < c+1; i++){
if(b[c-i] == r)
goto nextRow;
}
for (int i = 1; i < 8; i++){
if((b[c]-i) < 0 || (c-i) < 0)
break;
if(b[c]-i == b[c-i])
goto nextRow;
}
for (int i = 1; i<8; i++){
if((c-i) < 0 || (b[c]+i) > 7)
break;
if(b[c-i] == b[c]+i)
goto nextRow;
}
goto nextCol;
backtrack: c--;
if(c < 0)
return 0;
r = b[c];
goto nextRow;
print: static int numSolutions = 0;
cout << "Solution #" << ++numSolutions << ":" << endl;
for(int i = 0; i < 8; i++)
cout << b[i];
cout << endl;
goto backtrack;
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
