【问题标题】:Sudoku solver backtracking数独求解器回溯
【发布时间】:2023-03-27 04:25:01
【问题描述】:

我正在浏览一些数独求解器,我正在寻找一个使用回溯的解决方案,现在我找到了这段代码,但我不确定它是使用回溯还是其他算法?

感谢您的帮助。

abstract class SudoKiller {
private SudokuBoard sb;    // Puzzle to solve;

public SudoKiller(SudokuBoard sb) {
    this.sb = sb;
}


private boolean check(int num, int row, int col) {
    int r = (row / sb.box_size) * sb.box_size;
    int c = (col / sb.box_size) * sb.box_size;

    for (int i = 0; i < sb.size; i++) {
        if (sb.getCell(row, i) == num ||
            sb.getCell(i, col) == num ||
            sb.getCell(r + (i % sb.box_size), c + (i / sb.box_size)) == num) {
            return false;
        }
    }
    return true;
}


public boolean guess(int row, int col) {
    int nextCol = (col + 1) % sb.size;
    int nextRow = (nextCol == 0) ? row + 1 : row;

    try {
        if (sb.getCell(row, col) != sb.EMPTY)
            return guess(nextRow, nextCol);
    }
    catch (ArrayIndexOutOfBoundsException e) {
            return true;
    }

    for (int i = 1; i <= sb.size; i++) {
        if (check(i, row, col)) {
            sb.setCell(i, row, col);
            if (guess(nextRow, nextCol)) {
                return true;
            }
        }
    }
    sb.setCell(sb.EMPTY, row, col);
    return false;
}
}

如果这不是回溯,有没有一种简单的方法可以“转换”到它?

整个项目可以在the authors site找到。

【问题讨论】:

  • 你看过回溯的定义吗?

标签: java backtracking sudoku


【解决方案1】:

看起来它通过递归进行回溯。

我们向前一步:

sb.setCell(i, row, col);

在这里我们退后一步:

sb.setCell(sb.EMPTY, row, col);

【讨论】:

  • 怎么看出是回溯算法呢?有没有办法添加延迟,以便我可以实时看到回溯(当它发生时)。
  • @BobSmith 为答案添加了更多详细信息。
猜你喜欢
  • 2017-12-16
  • 1970-01-01
  • 1970-01-01
  • 2021-12-11
  • 2014-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多