#include <iostream> #include <cmath> using namespace std; int main(){ int b[8][8
ID: 3882808 • Letter: #
Question
#include <iostream>
#include <cmath>
using namespace std;
int main(){
int b[8][8] = {0}; //Setting up the board in 2D
int r, c=0; //Initial value of row and column are zeros.
b[0][0]=1; //Put the queen at the first box, at 0,0.
NC: c++;
if (c==8)
goto Print;
r=-1;
NR: r++;
if (r==8)
goto backtrack; //wrong
//row test
for (int i = 0; i<c; i++){
if (b[r][i]==1) goto NR;
}
//up diagnal test
for (int i = 1; (r-1)>=0 && (c-1)>=0; i++){
if (b[r-1][c-i]=1)
goto NR;
}
// down diagnal test
for (int i = 1; (r+i)<=7 && (c-1)>=0; i++){
if (b[r+i][c-i]=1)
goto NR;
}
if(b[r][c]=1)
goto NC;
backtrack:
c--;
if(c==-1)
return 0;
r = 0;
while (b[r][c]!=1)
r++;
b[r][c]=0;
goto NR;
cout << b[r][c] ;
Print:
cout << b[r][c];
goto backtrack;
}
Here is my codes for the 8 queens problem, however I am having a hard time to find out how to print the result, I already know the result is 92 but still not able to find a way to print. Can any expert help me find out what is wrong with my codes? Thank you!
Explanation / Answer
#include <iostream>
#include <cstdio>
#include <cstdlib>
#define N 8
using namespace std;
void displayOutput(int B[N][N])
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
cout<<B[i][j]<<" ";
cout<<endl;
}
}
bool isCheck(int board[N][N], int row, int col)
{
int i, j;
for (i = 0; i < col; i++)
{
if (B[row][i])
return false;
}
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
{
if (B[i][j])
return false;
}
for (i = row, j = col; j >= 0 && i < N; i++, j--)
{
if (B[i][j])
return false;
}
return true;
}
bool Util(int B[N][N], int col)
{
if (col >= N)
return true;
for (int i = 0; i < N; i++)
{
if ( isCheck(B, i, col) )
{
B[i][col] = 1;
if (Util(B, col + 1) == true)
return true;
B[i][col] = 0;
}
}
return false;
}
bool solveNqProblem()
{
int B[N][N] = {0};
if (Util(B, 0) == false)
{
cout<<"Solution does not exist"<<endl;
return false;
}
displayOutput(B);
return true;
}
int main()
{
solveNqProblem();
return 0;
}
Out Put :
1 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0
0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 0
0 0 0 1 0 0 0 0
0 0 0 0 0 1 0 0
0 0 1 0 0 0 0 0
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.