本文介绍了延迟递归回溯Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我发现了这个数独解算器,它在尝试解决难题时会使用回溯,为了更好地理解,我想延迟此过程,以便分析回溯.但是我真的不知道该怎么做.我尝试使用Thread.sleep(100);,但我真的不知道确切在哪里放置延迟.

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

整个项目可以在作者网站上找到.

推荐答案

在这里怎么样:

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

注意sleep有一个异常需要处理(即使未抛出),因此最简单的解决方案是:

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)) {

也就是说:

  • set
  • 之后
  • 递归调用之前
  • After a set and
  • Before a recursive call

以上两种情况中的一种或两种通常都是很好的候选人(视情况而定).

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

您甚至可以将其放在setCell方法的内部 .

You might even put it inside the setCell method.

这篇关于延迟递归回溯Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 02:35