Java Reference
In-Depth Information
Check each cell. Each cell must be a number from 1 to 9 and the cell must be unique
on every row, every column, and every small box.
A solution grid is
{{ 5 , 3 , 4 , 6 , 7 , 8 , 9 , 1 , 2 },
{ 6 , 7 , 2 , 1 , 9 , 5 , 3 , 4 , 8 },
{ 1 , 9 , 8 , 3 , 4 , 2 , 5 , 6 , 7 },
{ 8 , 5 , 9 , 7 , 6 , 1 , 4 , 2 , 3 },
{ 4 , 2 , 6 , 8 , 5 , 3 , 7 , 9 , 1 },
{ 7 , 1 , 3 , 9 , 2 , 4 , 8 , 5 , 6 },
{ 9 , 6 , 1 , 5 , 3 , 7 , 2 , 8 , 4 },
{ 2 , 8 , 7 , 4 , 1 , 9 , 6 , 3 , 5 },
{ 3 , 4 , 5 , 2 , 8 , 6 , 1 , 7 , 9 }
};
F IGURE 7.6
A solution is stored in grid .
The program in Listing 7.4 prompts the user to enter a solution and reports whether it is
valid. We use the second approach in the program to check whether the solution is correct.
L ISTING 7.4 CheckSudokuSolution.java
1 import java.util.Scanner;
2
3 public class CheckSudokuSolution {
4
public static void main(String[] args) {
5
// Read a Sudoku solution
6
7
8 System.out.println(
int [][] grid = readASolution();
read input
isValid(grid)
? "Valid solution" :
solution valid?
9
"Invalid solution" );
10 }
11
12
/** Read a Sudoku solution from the console */
13
14 // Create a Scanner
15 Scanner input = new Scanner(System.in);
16
17 System.out.println( "Enter a Sudoku puzzle solution:" );
18 int [][] grid = new int [ 9 ][ 9 ];
19 for ( int i = 0 ; i < 9 ; i++)
20 for ( int j = 0 ; j < 9 ; j++)
21 grid[i][j] = input.nextInt();
22
23
public static int [][] readASolution() {
read solution
return grid;
24 }
25
26
/** Check whether a solution is valid */
27
28 for ( int i = 0 ; i < 9 ; i++)
29 for ( int j = 0 ; j < 9 ; j++)
30 if (grid[i][j] < 1 || grid[i][j] > 9
31 || !isValid(i, j, grid))
32
public static boolean isValid( int [][] grid) {
check solution
return false ;
33
return true ; // The solution is valid
34 }
35
36
/** Check whether grid[i][j] is valid in the grid */
37
38
public static boolean isValid( int i, int j, int [][] grid) {
// Check whether grid[i][j] is valid in i's row
Search WWH ::




Custom Search