第八章第二十四题(检验数独的解决方案)(Solutions to test Sudoku)

第八章第二十四题(检验数独的解决方案)(Solutions to test Sudoku)

  • *8.24(检验数独的解决方案)程序清单8-4通过检测棋盘上的每个数字是否是有效的,从而检验一个解决方案是否是有效的。重写该程序,通过检验是否每行、每列以及每个小的方盒中具有数字1到9来检测解决方案的有效性。
    *8.24(Solutions to test Sudoku)Listing 8-4 verifies that a solution is valid by checking that each number on the chessboard is valid. Rewrite the program to test the effectiveness of the solution by verifying that there are numbers 1 to 9 in each row, column, and small box.

  • 参考代码:

    package chapter08;
    
    import java.util.Scanner;
    
    public class Code_24 {
        public static void main(String[] args) {
            int staSum = 45;
            int[][] matrix = new int[9][9];
            System.out.println("Enter a Sudoku puzzle solution:");
            Scanner cin = new Scanner(System.in);
            int sum = 0;
            boolean flag = false;
            for(int i = 0; i < 9; ++i){
                sum = 0;
                for(int j = 0; j < 9; ++j){
                    matrix[i][j] = cin.nextInt();
                    sum += matrix[i][j];
                }
                if(sum != staSum)
                    flag = true;
            }
    
            if (!flag){
                for(int i = 0; i < 9; ++i){
                    sum = 0;
                    for(int j = 0; j < 9; ++j){
                        sum += matrix[j][i];
                    }
                    if(sum != staSum){
                        flag = true;
                        break;
                    }
                }
            }
            if(flag)
                System.out.println("invalid solution");
            else
                System.out.println("valid solution");
        }
    }
    
    
  • 结果显示:

    Enter a Sudoku puzzle solution:
    9 6 3 1 7 4 2 5 8 
    1 7 8 3 2 5 6 4 9
    2 5 4 6 8 9 7 3 1
    8 2 1 4 3 7 5 9 6
    4 9 6 8 5 2 3 1 7
    7 3 5 9 6 1 8 2 4
    5 8 9 7 1 3 4 6 2
    3 1 7 2 4 6 9 8 5
    6 4 2 5 9 8 1 7 3
    invalid solution
    
    Process finished with exit code 0
    
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值