Delay recursive backtracking java

我的梦境 提交于 2019-12-24 08:23:17

问题


I found this sudoku solver which use backtracking when it is trying to solve the puzzle and for better understanding I would like to delay the process so I can analyse the backtracking. But I don't really know how to do that. I tried to use Thread.sleep(100); but I don't really know where exactly to put the delay.

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 whole project can be found on the authors site.


回答1:


How about here:

sb.setCell(i, row, col);
Thread.sleep(100);
if (guess(nextRow, nextCol)) {

Note sleep has an exception that needs to be handled (even if not thrown), so the simplest solution:

sb.setCell(i, row, col);
try { Thread.sleep(100); } catch(InterruptedException e) {}
if (guess(nextRow, nextCol)) {

That is:

  • After a set and
  • Before a recursive call

Either or both of the above are generally good candidates (depending on the situation).

You might even put it inside the setCell method.



来源:https://stackoverflow.com/questions/14923701/delay-recursive-backtracking-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!