第八章第二十四题(检验数独的解决方案)(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