数独回溯 无效数独

2024-04-23

我创建了一个数独回溯求解器,它工作得很好, 但现在如果数独无法解决,我想给出一个错误,因为它无效 例如,如果给出这个数独:

http://img5.imageshack.us/img5/2241/sudokugq.jpg http://img5.imageshack.us/img5/2241/sudokugq.jpg

如果无法解决,我该怎么做才能使我的解决方法给出错误? 我总是以零结束或陷入循环。

    public void solve( int row, int col ) throws Exception
   {
      // Throw an exception to stop the process if the puzzle is solved
      if( row > 8 ){
        //Gelöst
      }
      // If the cell is not empty, continue with the next cell
      if( sudo[row][col] != 0 ){
         next( row, col ) ;
        }
      else
      {
         // Find a valid number for the empty cell
         for( int num = 1; num < 10; num++ )
         {
            if( checkHorizontal(row,num) == false && checkVertikal(col,num)== false&& checkBox(row,col,num)== false )
            {
               sudo[row][col] = num ;


               // Delegate work on the next cell to a resudosive call
               next( row, col ) ;
            }
         }

         // No valid number was found, clean up and return to caller
         sudo[row][col] = 0 ;
      }

   }

   //Ruft solve für das nächste Feld auf
   public void next( int row, int col ) throws Exception
   {
      if( col < 8 )
         solve( row, col + 1 ) ;
      else
         solve( row + 1, 0 ) ;
   }

当然当你击中sudo[row][col] = 0 ;代码你刚刚尝试完一个正方形中的每个值,但没有发现其中任何一个的解决方案。当然,这就是你决定放弃并处于无解状态的时刻。

进一步思考——我怀疑我只是接近正确。如果你点击这个代码and这是first您正在尝试的单元格(即您找到的第一个空单元格)那么这就是您的失败时刻。

顺便说一句 - 我不确定使用异常来指示您在评论中建议的解决方案是个好主意。


现在,这正确地拒绝了您发布的板 - 请注意,不仅第一行有两个“3”,第一列也有两个“5”。这段代码现在似乎对我有用。也许你可以在一种不溶性的物质上尝试一下。

public class Test {

    static final int S = 9;
    int[][] sudo;

    public Test() {
        // Just leave it empty.
        sudo = new int[S][S];
    }

    public Test(int[][] sudo) {
        this.sudo = sudo;
    }

    // This number should not appear anywhere in the row.
    public boolean checkHorizontal(int row, int num) {
        for (int i = 0; i < S; i++) {
            if (sudo[row][i] == num) {
                return false;
            }
        }
        return true;
    }

    // This number should not appear anywhere in the col.
    public boolean checkVertical(int col, int num) {
        for (int i = 0; i < S; i++) {
            if (sudo[i][col] == num) {
                return false;
            }
        }
        return true;
    }

    // This number should not appear anywhere in the box.
    private boolean checkBox(int row, int col, int num) {
        // Round down to nearest 3.
        int r = (row / 3) * 3;
        int c = (col / 3) * 3;
        for (int i = r; i < r + 3; i++) {
            for (int j = c; j < c + 3; j++) {
                if (sudo[i][j] == num) {
                    return false;
                }
            }
        }
        return true;
    }

    boolean check(int row, int col, int num) {
        // All checks must pass.
        return checkHorizontal(row, num)
                && checkVertical(col, num)
                && checkBox(row, col, num);
    }

    public boolean solve(int row, int col) {
        // Got to the end?
        if (row >= S) {
            //Gelöst
            return true;
        }
        // If the cell is empty
        if (sudo[row][col] == 0) {
            // Find a valid number for the empty cell
            for (int num = 1; num < 10; num++) {
                // Can this number be put there?
                if (check(row, col, num)) {
                    // Yes!
                    sudo[row][col] = num;
                    // Try that.
                    if (next(row, col)) {
                        return true;
                    }
                }
            }
            // Clean up.
            sudo[row][col] = 0;
        } else {
            // Move on.
            if (next(row, col)) {
                return true;
            }
        }
        // Failed to find a solution.
        return false;
    }

    //Ruft solve für das nächste Feld auf
    public boolean next(int row, int col) {
        if (col < S - 1) {
            // Step right.
            return solve(row, col + 1);
        } else {
            // Step down.
            return solve(row + 1, 0);
        }
    }

    public boolean boardOk() {
        // Initial test to ensure it is a valid array.
        // Must have that many rows.
        boolean ok = sudo.length == S;
        for (int row = 0; ok && row < S; row++) {
            // Each row must be that long.
            ok &= sudo[row].length == S;
            for (int col = 0; ok && col < S; col++) {
                // Each filled square must be valid.
                if (sudo[row][col] != 0) {
                    int num = sudo[row][col];
                    // Remove it.
                    sudo[row][col] = 0;
                    // Check it can be added.
                    ok &= check(row, col, num);
                    // Put it back.
                    sudo[row][col] = num;
                }
            }
        }
        return ok;
    }

    void solve() {

        if (boardOk()) {
            boolean solved = solve(0, 0);
            if (solved) {
                System.out.println("Solved!");
                print();
            }
        } else {
            System.out.println("Insoluble!");
            print();
        }
    }

    public void print() {
        for (int i = 0; i < sudo.length; i++) {
            System.out.println(Arrays.toString(sudo[i]));
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Test().solve();
        int[][] test = {
            {0, 0, 6, 5, 8, 3, 3, 2, 7},
            {0, 0, 0, 0, 9, 0, 0, 5, 0},
            {5, 8, 0, 0, 0, 0, 0, 0, 3},
            {0, 3, 1, 0, 4, 0, 5, 0, 0},
            {0, 0, 0, 9, 2, 0, 3, 0, 6},
            {0, 0, 0, 0, 0, 0, 0, 0, 1},
            {3, 4, 2, 0, 0, 6, 9, 1, 5},
            {5, 0, 5, 4, 0, 9, 0, 3, 2},
            {0, 1, 0, 0, 0, 0, 0, 0, 4},};
        new Test(test).solve();
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

数独回溯 无效数独 的相关文章

随机推荐

  • 如何让我的 NPM 包在本地安装时显示“npm WARN Preferred Global”

    很难用谷歌搜索这个主题 太多的用户问题 我的问题是关于包开发的 我想让我的包的用户看到 npm WARN 更喜欢全局 当不是全局安装时 我想npm install yo以前有这样的警告 但现在没有了 至少我看不到 我的环境 npm vers
  • 在 C# 中是否有更简单的方法为函数指定别名

    背景 在我移植的API中 有大量以sqlite3 为前缀的函数 它们被封装在一个名为Sqlite3的类中 因此函数调用为Sqlite3 sqlite3 我创建了许多别名调用 类似于以下内容 C alias for call public s
  • 使用 jQuery 获取下一个同级的文本

    我正在尝试获得下一节项目标题 section project title并回应它 为了便于阅读 我的标记已被删除 但它的结构仍然存在 我能够获取下面的部分项目标题 section activediv 但不知道如何抓住next项目名称 请注意
  • 来自远程客户端的 websphere jms 队列访问

    背景我是 php 和前端 Web 开发人员 使用 Netbeans 开发 Java 应用程序 从 websphere 我认为是 V8 5 JMS 队列中读取数据 然后向适当的脚本 服务器发出命令 这是我大约 10 年来第一次主要接触 Jav
  • android中invalidateOptionsMenu()有什么用

    我是android的新手 当我浏览导航抽屉的示例代码时 我发现他调用了方法invalidateOptionsMenu 所以我搜索了它的功能 但找不到答案 所以任何人都可以向我介绍一下它的功能以及我们什么时候应该这样做吗 用那个 这个函数告诉
  • 无法通过 python-jira lib 连接到 JIRA-api

    我无法对 python jira 进行身份验证 我尝试使用https pypi python org pypi jira https pypi python org pypi jira 根据我使用的文档 from jira import J
  • 如何使用 PHP 读取来自 Stackoverflow API 的 GZIP 响应?

    如何使用 PHP 读取 Stackoverflow API 的响应 响应是 GZIP 编辑的 我发现例如以下建议 url http api stackoverflow com 1 1 questions question id data f
  • iOS NSDate 仅包含时间字符串

    我的任务是将带有时间的字符串解析为 NSDate 我用以下代码做得很好 NSString timeStr 15 00 00 NSDateFormatter formatter NSDateFormatter alloc init forma
  • Python Pandas 用缺失值填充数据框

    我有这个数据框作为例子 import pandas as pd create dataframe df pd DataFrame DE Table 201705 201705 1000 DE Table 201705 201704 1000
  • 如何在 android studio 中禁用 gradle '离线模式'? [复制]

    这个问题在这里已经有答案了 我是 android studio IDE 开发的新手 每次当我导入在 android studio 中开发的示例项目时 我都会收到此错误 没有缓存版本com android tools build gradle
  • jQuery 和使用速记设置 CSS

    来自 Pro PHP 和 jQuery 提示 返回的值是 CSS 简写属性 3 添加了一个 jQuery 的好处是能够使用 CSS 设置 CSS 属性 简写 它不适用于基本的 JavaScript 来自 jQuery API 参考 简写 C
  • 使用 sapply 时,我在 str2lang(x) 中收到错误: :1:31: 意外符号 1 ^

    当运行这段代码时 我会得到一个错误 genes lt colnames survdata c 1 3 univ formulas lt sapply genes function x as formula paste Surv OS sta
  • 如何在 Electron 桌面应用程序中使用 Google 登录?

    我正在使用 Node js 和 Express 制作一个简单的应用程序 它严重依赖 Google 登录来获取个人资料图片和昵称 当在新的 Electron 应用程序中测试它时 我遇到了错误 此浏览器或应用程序可能不安全 尝试使用不同的浏览器
  • mockito-core 与mockito-inline 之间的区别

    在我的项目中 我们已经有了mockito core依赖项 我想存根静态方法 我需要为其添加模拟内联依赖项 所以想了解一下它们之间的区别 它们可以共存吗 根据版本 4 2 0 的最新文档 mockito 社区似乎已经提出了 mockito i
  • FQL 流查询中 Facebook 帖子展示次数为空

    根据FQL 流文档 http developers facebook com docs reference fql stream 以下查询应该在由经过身份验证的页面所有者运行时返回展示计数 但它从未返回 我们让页面所有者直接在图形 API
  • 什么场景下才需要使用“方法隐藏”? [复制]

    这个问题在这里已经有答案了 可能的重复 隐藏在 C 中的方法并带有有效示例 为什么它在框架中实现 现实世界的优势是什么 https stackoverflow com questions 1193848 method hiding in c
  • 如何将数字(如 int)转换为“Number”?

    这可能是基本问题 但我找不到有用的东西 问题是 如何转换double or int价值Number类型 更具体地说oracle jbo domain Number 我尝试了以下方法 对于整数值 int i 9 Integer y new I
  • 如何通过 Angular 2+ 中的单元测试避免依赖地狱

    我看到很多关于如何在 Angular 2 中对简单组件进行单元测试的示例 但是当涉及到使用服务的测试组件时 维护测试床提供程序和导入就变成了一场噩梦 我怎样才能避免它 例如 我有 myComponents 它使用 myService 它使用
  • 什么定义了实时/近实时系统?

    系统是否应满足特定的指标才能被视为 分类为实时 Web 应用程序或近实时 Web 应用程序 当我看到我正在使用的系统的非功能性需求表明解决方案应实时 接近实时返回数据时 我理解这些术语的定义 如发现http en wikipedia org
  • 数独回溯 无效数独

    我创建了一个数独回溯求解器 它工作得很好 但现在如果数独无法解决 我想给出一个错误 因为它无效 例如 如果给出这个数独 http img5 imageshack us img5 2241 sudokugq jpg http img5 ima