Asking for help to troubleshoot a c++ Eight queens puzzle code

后端 未结 1 1232
天命终不由人
天命终不由人 2020-12-18 08:21

I have written a function in C++ code for the eight queens problem. The program is supposed to print out all 92 possible solutions. I only can run up to 40. Don\'t know w

相关标签:
1条回答
  • 2020-12-18 08:35

    Your problem is in the ok function. It has three errors, all relating to the bounds of your matrix. The first error (which will if anything cause you to receive too many solutions), is here:

    for(int c = 7; c > 0; c--){
    

    This will never check column 0. The test should be c >= 0.

    The other two errors, which cause unpredictable behavior, are here:

        for(int i = 1; i <= c; i++){
            if(board[r][c-i] == 1)
                return false;
            else if (board[r-i][c-i] == 1)
                return false;
            else if (board[r+i][c-i] == 1)
                return false;
        } // for loop
    

    This can cause the ok function to return an arbitrary number of false negatives. In my case, compiling and running your program with these two errors produced no solutions. It is only by chance that it produces 40 solutions for you.

    The problem is again with bounds. The i variable is moving from 1 up to and including c, so c-i moves down from c-1 to 0, as intended.

    However, you are not checking that r-i and r+i remain within the bounds of the matrix. Consider the case that r = 7 and i = 4. Then, r+i = 11, which runs past the end of the row. Similarly, if r = 0 and i is anything other than 0, r-i will be negative and run past the beginning of the row.

    You need to add additional checks to make sure that the row values used in the tests within this loop are within the range 0 to 7. You can take advantage of the short-circuiting behavior of the logical operators in C++ to do this, for example:

     else if (<test> && board[r-i][c-i] == 1)
    

    will examine board[r-i][c-i] only if <test> is true.

    I'm leaving adding the corrections to these second two errors as an exercise for you, since this is very likely to be a homework assignment (and if it is, you should add the [homework] tag to the question).

    0 讨论(0)
提交回复
热议问题