java – 递归回溯何时适用?

我正在为一个类创建一个SudokuSolver,我在解决方法上遇到麻烦.我目前的解决方案使用递归回溯(我认为).

作业要求

int solve() — tries to solve the puzzle using the strategy described above. Returns the number of solutions.

(上述策略)

When assigning a number to a spot,never assign a number that,at that moment,conflicts with the spot’s row,column,or square. We are up-front careful about assigning legal numbers to a spot,rather than assigning any number 1..9 and finding the problem later in the recursion. Assume that the initial grid is all legal,and make only legal spot assignments thereafter.

心理思想

我可以迭代地跟随一个小的输入.例如,说我必须未解决的单元格#1和单元#2. #1有可能{1,3}和#2有可能{2,3}.我会的

set 1 to 1
    set 2 to 2
        hasConflicts? 0 : 1
    set 2 to 3
        hasConflicts? 0 : 1
set 1 to 3
    set 2 to 2
        hasConflicts? 0 : 1
    set 2 to 3
        hasConflicts? 0 : 1

实际代码

public int solve() {
    long startTime = System.currentTimeMillis();
    int result = 0;

    if (!hasConflicts()) {
        Queue<VariableCell> unsolved = getUnsolved();
        reduceUnsolvedPossibilities(unsolved);  // Gets the possibilities down from all of 1-9

        if (!hasConflicts()) {
            result = solveRec(unsolved);
        }
    }

    mElapsedTime = System.currentTimeMillis() - startTime;
    return result;
}

protected int solveRec(Queue<VariableCell> unsolved) {
    if (unsolved.isEmpty()) {
        return (hasConflicts()) ? 0 : 1;
    }

    int result = 0;
    VariableCell cell = unsolved.remove();
    Iterator<String> possibilityIt = cell.getPossibilities().iterator();

    while (possibilityIt.hasNext()) {
        cell.setSymbol(possibilityIt.next());

        if (hasConflicts()) {
            possibilityIt.remove();
        } else {
            ++result;
        }
    }

    return result + solveRec(unsolved);
}

检测结果

testSolveSingleSolution
    expected 1,actual 1

testSolveSolved
    expected 1,actual 1

testSolveUnsolvable
    expected 0,actual 0

testSolveMultiSolutions
    expected 2,actual 7  // MAJOR PROBLEM!

递归回溯的一些很好的解释

> This answer to StackOverflow – Sudoku发生器的递归解决方案
> This answer到StackOverflow – 在迷宫中的BackTracking
> This answer到StackOverflow – 主序列的回溯算法
> This answer到StackOverflow – 如何找到第一个解决方案只有这个回溯
>维基百科文章Backtracking
> Recursive Backtracking Explanation

我之前已经进行了递归回溯,我已经看过上面的所有链接,我仍然有麻烦.我认为问题在于我如何解决这个问题. (参见Psudeocode Idea.)是否适合使用递归回溯进行详尽的搜索?追溯权是否正确执行错误?我可以使用比递归回溯更好的算法吗?先谢谢了!

解决方法

这看起来像一个实现问题.检查块的结果增加.你真的要增加那个单元格的每个有效值吗?如果有几个有效值,那么覆盖旧的有效值呢?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


eclipse如何打jar包
eclipse如何查看源码
如何评价java框架的质量?
Spring MVC 和 Spring Security 有何区别?
eclipse如何运行java代码
eclipse的jdk如何配置
eclipse如何部署web项目
如何使用eclipse编程
eclipse如何导入svn项目
eclipse如何打开项目
eclipse如何添加svn
java中用于日志记录的框架有哪些?
eclipse如何更改jdk
如何在eclipse中配置svn
eclipse如何添加sdk
java框架中如何实现高并发?
eclipse如何配置python
java框架有哪些用于人工智能和机器学习的类型?
eclipse如何配置git
eclipse如何添加jdk