-1

Here is the method, it ideally should solve the eight-queens problem by placing Qs on the board so that none of them threaten each other, but I can't seem to stop it from infinitely recursing.

public static void solve(int row, int col, int size, char[][] array) {
    for (int i = 0; i < size - 2; i++) {
        if (isSafe(row, col, size, array)) {
            array[i][col] = 'Q';
        } else {
            if (col < size - 2) {
                solve(row, col++, size, array); //changed ++ to +1
            }
        }
    }
}

For clarity, here is the included 'isSafe' method:

public static boolean isSafe(int row, int col, int size, char[][] array) {
    //check column
    for (int i = 0; i < size - 1; i++) {
        if (array[i][col] == 'Q') {
            return false;
        }
    }
    //horizontal
    for (int i = size - 1; i >= 0; i--) {
        if (array[row][i] == 'Q') {
            return false;
        }
    }
    //up diagonal
    while (row > 0 && col > 0) {
        int x = row;
        int y = col;
        if (array[row - 1][col - 1] == 'Q') {
            return false;
        } else {
            x--;
            y--;
        }
    }
    //down diagonal
    while (row < size - 1 && col > 0) {
        int x = row;
        int y = col;
        if (array[row + 1][col - 1] == 'Q') {
            return false;
        } else {
            x++;
            y--;
        }
    }
    return true;
}

Thank you for any light you can shed on this.
EDIT : So I just figured out that by changing '++' to '+1' I was able to stop the stack overflow, but my method does not recurse like I want it to so a question still remains

  • 8
    Possible duplicate of [What is a debugger and how can it help me diagnose problems?](http://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Raedwald Mar 22 '17 at 13:53
  • "Still doesn't recurse[sic] like I want it" is not a problem specification. Show the output and your debugging trace. – Prune Mar 22 '17 at 16:18

1 Answers1

0

The problem is with solve(row, col++, size, array); col will not be incremented until AFTER the call to solve. You need to use solve(row, ++col, size, array);

jr593
  • 287
  • 1
  • 8