Q # 1 : Complete the 8 queens 1 dimensional array program with backtracking REMO
ID: 3548878 • Letter: Q
Question
Q # 1 : Complete the 8 queens 1 dimensional array program with backtracking REMOVING ALL "GOTOs" please fix the below program with backtracking removing all gotos and also run the program before posting it and please comment before each line or explain such as what this line means or does . #include <iostream> using namespace std; int main() { int q[8], c, i, j; q[0] = 0; c = 0; goto nextColumn: c++; if( c == 8 ) goto print; q[c] = -1; goto nextRow: q[c]++; if( q[c] == 8 ) goto backtrack; //row test for( int i=0 ;i<c;i++) if (q[i]== q[c]) goto nextColumn; for(int i =0 ; i<0 ;i++) if ((c-i)==(q[c]-q[i])) goto nextColumn; for(int i=0; i<c; i++) if(q[i] == q[c] || (c-i) == abs(q[c]-q[i])) goto nextRow; backtrack: c--; if(c == -1) return 0; goto nextRow; print: for(int j=0; j<8; j++) { cout << q[j] << " "; cout << endl; } return 0; }
Explanation / Answer
#include <iostream>
#include<math.h>
using namespace std;
void nextColumn();
void nextRow();
void backtrack();
void print();
int q[8], c, i, j;
void nextColumn()
{
c++;
if( c == 8 )
print();
else
q[c] = -1;
}
void nextRow()
{
q[c]++;
if( q[c] == 8 )
backtrack();
//row test
for( int i=0 ;i<c;i++)
if (q[i]== q[c])
nextColumn();
for(int i =0 ; i<0 ;i++)
if ((c-i)==(q[c]-q[i]))
nextColumn();
}
void backtrack()
{
c--;
if(c == -1)
return ;
else
nextRow();
}
void print()
{
for(int j=0; j<8; j++)
{
cout << q[j] << " ";
cout << endl;
}
}
int main()
{
q[0] = 0;
c = 0;
nextColumn();
nextRow();
for(int i=0; i<c; i++)
if(q[i] == q[c] || (c-i) == abs(q[c]-q[i]))
nextRow();
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.