In: Computer Science
Need this 8 queen code with same exact solution without goto.
Need to keep the code as similar as possible.
#include <iostream>
#include <cmath>
using namespace std;
int main(){
int q[8], c = 0, i, j,count=0;
q[0] = 0; //first queen top corner
nc: c++;
if(c == 8 ) goto print;
q[c] = -1;
nr: q[c]++;
if(q[c] == 8) goto backtrack;
for(i= 0; i < c; i++) {
if((q[i] == q[c])||(c - i == abs(q[c] - q[i]))) goto nr;
}
goto nc;
backtrack: c--;
if(c == -1) return 0;
goto nr;
print: cout << ++count <<endl;
for(i = 0; i < 8; i++){
for(j= 0; j < 8; j++){
if(q[i] == j){
cout << 1;
}
else {
cout << 0;
}
}
cout << endl;
}
goto backtrack;
}
#include<iostream>
#include<cmath>
using namespace std;
int q[8],c=0,i,j,count=0;
q[0]=0;
void nc()
{
c++;
}
void nr()
{
q[c]++;
}
void backtrack()
{
c--;
}
void print()
{
cout<<++count<<endl;
}
int main()
{
if(c==8) print();
q[c]=-1;
if(q[c]==8) backtrack();
for(i=0;i<c;i++)
{
if((q[i]==q[c])||(c-i==abs(q[c]-q[i])))
nr();
}
nc();
if(c==-1)
return 0;
nr();
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
{
if(q[i]==j)
{
cout<<1;
}
else
{
cout<<0;
}
}
cout<<endl;
}
backtrack();
}
Reference :
Explanation :
I have used functions to avoid goto statement. Just used function calling in the place of goto statement .
I didn't change the code , just declared the functions and variables out of the main function .