Java Reference
In-Depth Information
To find a solution for the puzzle, we must replace each
0
in the grid with an appropriate
number from
1
to
9
. For the solution to the puzzle in Figure 8.5, the grid should be as shown
in Figure 8.6.
Once a solution to a Sudoku puzzle is found, how do you verify that it is correct? Here are
two approaches:
Check if every row has numbers from
1
to
9
, every column has numbers from
1
to
9
,
and every small box has numbers from
1
to
9
.
■
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
8.6
A solution is stored in
grid
.
The program in Listing 8.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
8.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
int
[][] grid = readASolution();
read input
7
8 System.out.println(isValid(grid) ?
"Valid solution"
:
9
solution valid?
"Invalid solution"
);
10 }
11
12
/** Read a Sudoku solution from the console */
13
public static int
[][] readASolution() {
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
read solution
return
grid;
24 }
25
26
/** Check whether a solution is valid */
27
public static boolean
isValid(
int
[][] grid) {
check solution
Search WWH ::
Custom Search