Question: Listing 8.4 checks whether a solution is valid by checking whether every number is valid in the board. Rewrite the program by checking whether every

Listing 8.4 checks whether a solution is valid by checking whether every number is valid in the board. Rewrite the program by checking whether every row, every column, and every small box has the numbers 1 to 9.

Listing

1 import java.util.Scanner; 2 3 public class CheckSudokuSolution { public static void

main(String[] args) { // Read a Sudoku solution int [] [] grid

1 import java.util.Scanner; 2 3 public class CheckSudokuSolution { public static void main(String[] args) { // Read a Sudoku solution int [] [] grid = readASolution(); 4 6 System.out.printIn(isValid(grid) ? "Valid solution" : "Invalid solution"); 8. 6. 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 /** Read a Sudoku solution from the console */ public static int[][] readASolution() { // Create a Scanner Scanner input = new Scanner(System.in); System.out.println("Enter a Sudoku puzzle solution:"); int [][] grid = new int[9] [9]; for (int i = 0; i < 9; i++) for (int j = 0; j < 9; j++) grid[i][j] = input.nextInt(); return grid; 26 /** Check whether a solution is valid */ 27 public static boolean isValid(int[][] grid) { HNm 4567 ~~~2N~~ for (int i = 0; i < 9; i++) for (int j = 0; j < 9; j++) if (grid[i][j] < 1 || grid[i][j] > 9 Il !isValid(i, j, grid)) return false; return true; // The solution is valid 28 29 30 31 32 33 34 35 36 /** Check whether grid[i][j] is valid in the grid */ public static boolean isValid(int i, int j, int[][] grid) { // Check whether grid[i][j] is unique in i's row for (int column = 0; column < 9; column++) if (column != j && grid[i][co]umn] == grid[i][j]) return false; 37 38 39 40 41 42 43 // Check whether grid[i][j] is unique in j's column for (int row = 0; row < 9; row++) if (row != i && grid[row][j] == grid[i][j]) return false; 44 45 46 47 48 49 50 51 52 53 54 // Check whether grid[i][j] is unique in the 3-by-3 box for (int row = (i / 3) * 3; row < (i / 3) * 3 + 3; row++) for (int col = (j / 3) * 3; col < (j / 3) * 3 + 3; col++) if (row != i && col != j && grid[row][col] == grid[i][j]) return false; return true; // The current value at grid[i][j] is valid 55 } 56 } Enter a Sudoku puzzle solution: 9 6 3 17 4 2 5 8 -Enter 17 8 3 2 5 6 4 9 JEnter 25 4 6 8 97 31 -Enter 8 2 1 4 3 759 6 JEnter 4 9 6 8 52 317 JEnter 7 3596 1 8 2 4 -Enter 5 89 7 13 4 6 2 JEnter 3 17 2 4 69 8 5 -Enter 6 4 2 5 9 8 17 3 Valid solution LEnter

Step by Step Solution

3.34 Rating (175 Votes )

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

Program Plan Create readSolution method so that reads the solution from the user input and returns t... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Java Programming Questions!