Question

I am having trouble trying to make a certain for-loop continue to completion in the 1D Queens problem.

First, I used goto statements for everything. Now I am trying to get rid of the goto statements by using functions instead. I will eventually get rid of all of them, but I am focusing on NR (new row) and backtrack first, since they are meant to call each other.

The for loop I am having trouble with is the one that checks if a position is safe for a queen. I point out the for-loop that does not complete in the comments.

//forward declarations
int backtrack (int board[], int& c_position);

//NR: q[c]++;
//if (q[c]==8) goto backtrack;

void NR (int board[], int& c_position) //new row
{
    board[c_position]++;
    if (board[c_position]==8) {backtrack(board, c_position);}
}

int backtrack (int board[], int& c_position)  // backtrack
{
    c_position--;
    if (c_position==-1) {system("PAUSE"); exit(1);}
    NR(board, c_position);
}


int main ()
{

int q[8] = {0};  //1D array, the board, all set to 0;
int c=0;
int count=0;


NC: c++; //new column
    if (c==8) goto print;
    q[c]=-1;

NR(q, c);


    //test to see if position is safe
    for (int i=0; i<c; i++) //this is the for loop I am having trouble with
    {
    if ( (q[i]==q[c]) || ((c-i)==abs(q[c]-q[i])) ) { NR(q, c); }
    }

    goto NC;

print: //printing the 1D board gives us a single line, where each number represents a row where a queen is
        count++;
        cout << count << endl;
      for(int j = 0; j <= 7; j++)
      {
         cout << q[j] << " ";
      }
       cout << endl;
        backtrack(q, c);

        system("PAUSE"); return 0;

}
Was it helpful?

Solution

You're passing c by reference to a function that passes it to another function that decrements it.

That appears to foil your (outer goto-based) loop's attempt to increment it.

Anyway, that's what I'd look at more closely.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top