Search code examples
javadelaybacktracking

Delay recursive backtracking java


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.


Solution

  • 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.