As stated in the question, I am required by my professor to use goto statements.
ID: 3620188 • Letter: A
Question
As stated in the question, I am required by my professor to use goto statements. I don't understand why this isn't working. I believe I have written most of the code for this algorithm, but I have tested this in many different ways and it's compiling and returning nothing. I come from a Java background and just started doing c++, so my debugging skills are off, but i've tried debugging in every way I can think of. Best answer is Lifesaver worthy.Code:
//dumb 8 queens using a 2-dimensional array to represent the board
#include<cmath>
#include<iostream>
using namespace std;
int main()
{
int b[8][8]={0}, r, c, i;
b[0][0]=1;
c = 0;
NC: //next column
c++;
if(c==8)
goto print;
r=-1;
NR: //next row
r++;
if(r==8)
goto backtrack;
//1. row test
for(i=0; i<c; i++)
{
if(b[r][i]==1)
goto NR;
}
//2. up-diagonal test
for(i=1; (((r-i)>=0) && ((c-i)>=0));i++)
{
if(b[r-i][c-i]==1)
goto NR;
}
//3. down-diagonal test
for(i=1;(((r+i)<=7) && ((c-i)>=0)); i++)
{
if(b[r+i][c-i]==1)
goto NR;
b[r][c]=1;
goto NC;
}
backtrack:
c--;
if(c<0)
return 0;
r=0;
while(b[r][c] != 1)
r++;
b[r][c]=0;
goto NR;
print:
for(int i=0; i<8; i++)
{
for(int j=0; j<8; j++)
cout << b[i][j];
cout << endl;
}
return 0;
}//end main function
Explanation / Answer
#define N 8
int Chess(char Arr[N][N] , int row);
int check(char Arr[N][N],int row,int line);
//double count;
int main()
{
char chess[N][N]={0};
Chess(chess,0);/* The call to the function*/
{
int i,y;
for(i=0;i<N;++i)/*prints the result*/
{
cout<<" ";
for(y=0;y<N;++y)
{
if(chess[i][y]==0)
cout<<"x ";
else
cout<<chess[i][y];
}
}
}
cout<<" ";
system("pause");
}
int Chess(char Arr[N][N] , int row)
{
int line=0;
if(row==N)
return 1;
while(line < N)
{
if(check(Arr,row,line)) /*check the row*/
{
Arr[row][line]='Q'; /*puts a queen on the board*/
if(Chess(Arr,row+1))/*the recursion*/
return 1;
Arr[row][line]=0;/*clears the last change if*/
}/*returned 0 from the recursion*/
line++;
}
return 0;
}
int check(char Arr[N][N],int row,int line)
{
/*check just the left size of the board*/
int r,l;
r=row;
l=line;
while(r >= 0 && l >= 0)
{
if(Arr[r][l]=='Q')
return 0;
--r;
--l;
}
l=line;
r=row;
while(l < N && r >= 0)
{
if(Arr[r][l]=='Q')
return 0;
++l;
--r;
}
l=line;
r=row;
while(r >= 0)
{
if(Arr[r][l]=='Q')
return 0;
--r;
}
return 1;
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.