【问题标题】:Array from recursive call being overwritten递归调用的数组被覆盖
【发布时间】:2021-01-13 19:43:07
【问题描述】:

我们正在制作一个程序,通过带有回溯的递归方法来解决星号数独问题。

solveIt 方法调用solve 方法,这是递归方法。 grid 之前声明为一个 9x9 二维数组,其中包含要填充的拼图。如果有一个解决方案,程序必须打印出完成的拼图,但是如果有更多解决方案,它只能打印出可能的数量解决方案。

问题是:在solve 内部,print(); 工作得很好,可以打印出完整的拼图。然而,在该方法之外,它会打印出空的初始拼图。为什么是这样?我们无法弄清楚为什么在solve 完成时,一个单独的变量(在这种情况下为h)也会被随机覆盖。

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
    }
}

【问题讨论】:

    标签: java recursion multidimensional-array sudoku recursive-backtracking


    【解决方案1】:

    解决方案

    .clone() 方法似乎只是将h 引用到grid。所以h 指向grid 并采用它的值导致我们在上面遇到的问题。

    因此实施了以下解决方案:

    //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];
        }
    }
    

    更多信息clone()

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-18
      • 2011-12-13
      • 2020-07-07
      • 2012-05-09
      • 2018-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多