Array from recursive call being overwritten

122 views Asked by At

We're making a program to solve an asterisk sudoku via a recursive approach with back tracking.

The solveIt method calls the solve method which is the recursive method. grid is declared before to be a 9x9 2D array that contains the puzzle to be filled in. If there is one solution, the program must print out the completed puzzle however if there are more solutions it must only print out the number of possible solutions.

Question is: Inside of solve, print(); works just fine and prints out the complete puzzle. However outside of the method it prints out the empty initial puzzle. Why is this? We cannot figure out why a separate variable (h in this case) also gets randomly overwritten when solve completes.

int[][] h;
int solutionCounter = 0;

void solve() {
    int[] next = findEmptySquare();
    if (!(next[0] == -1 && next[1] == -1)) {
        if (grid[next[0]][next[1]] == 0) {
            for (int i = SUDOKU_MIN_NUMBER; i <= SUDOKU_MAX_NUMBER; i++) {
                if (!(givesConflict(next[0], next[1], i))) {
                    //fills in the puzzle
                    grid[next[0]][next[1]] = i;
                    //go to next number
                    solve();
                }
            }
            grid[next[0]][next[1]] = 0;
        }
    } else {
        //print(); here it works just fine
        solutionCounter++;
        h = grid.clone();
    }
}

void solveIt() {
    solve();
    if (solutionCounter > 1) {
        System.out.println(solutionCounter);
    } else {
        grid = h.clone();
        print(); //here it prints the empty puzzle
    }
}
1

There are 1 answers

0
Egor. L On BEST ANSWER

Solution

The .clone() method seems to simply reference h to grid. So h points to grid and takes on its values leading to the problem we were having above.

Therefore the following solution was implemented:

//copy the grid into h.
for (int x = 0; x < 9; x++) {
    for (int y = 0; y < 9; y++) {
        h[x][y] = grid[x][y];
    }
}

More information on clone():

https://www.geeksforgeeks.org/clone-method-in-java-2/