Java Reference
In-Depth Information
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
return false ;
33
return true ; // The solution is valid
34 }
35
36
/** Check whether grid[i][j] is valid in the grid */
37
public static boolean isValid( int i, int j, int [][] grid) {
38
// Check whether grid[i][j] is unique in i's row
check rows
39
for ( int column = 0 ; column < 9 ; column++)
40
if (column != j && grid[i][column] == grid[i][j])
41
return false ;
42
43
// Check whether grid[i][j] is unique in j's column
44
for ( int row = 0 ; row < 9 ; row++)
check columns
45
if (row != i && grid[row][j] == grid[i][j])
46
return false ;
47
48
// Check whether grid[i][j] is unique in the 3-by-3 box
49
for ( int row = (i / 3 ) * 3 ; row < (i / 3 ) * 3 + 3 ; row++)
check small boxes
50
for ( int col = (j / 3 ) * 3 ; col < (j / 3 ) * 3 + 3 ; col++)
51
if (row != i && col != j && grid[row][col] == grid[i][j])
52
return false ;
53
54
return true ; // The current value at grid[i][j] is valid
55 }
56 }
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
Valid solution
The program invokes the readASolution() method (line 6) to read a Sudoku solution
and return a two-dimensional array representing a Sudoku grid.
The isValid(grid) method checks whether the values in the grid are valid by verifying
that each value is between 1 and 9 and that each value is valid in the grid (lines 27-34).
The isValid(i, j, grid) method checks whether the value at grid[i][j] is valid.
It checks whether grid[i][j] appears more than once in row i (lines 39-41), in column j
(lines 44-46), and in the 3
isValid method
overloaded isValid method
3 box (lines 49-52).
How do you locate all the cells in the same box? For any grid[i][j] , the starting cell
of the 3
*
*
3 box that contains it is grid[(i / 3) * 3][(j / 3) * 3] , as illustrated in
FigureĀ 8.7.
 
 
Search WWH ::




Custom Search