CSC220 Lab 6
Due: 10:59AM, Tuesday, October 19
Your task is to write a code for solving Sudoku puzzles.
A Sudoku diagram is a 9 by 9 grid of numbers between 1 and 9 such that
-
in each column the numbers 1 through 9 appear exactly once each,
-
in each row the numbers 1 through 9 appear exactly once each,
-
when the grid is divided into 3 by 3 blocks by grouping
the top three rows, the middle three rows, and the bottom three rows
and grouping
the left three columns, the middle three columns, and the right three
columns, in each blck the numbers 1 through 9 appear exactly once each.
An input to Sudoku is a 9 by 9 grid with numbers hidden at some locations
and its solution is a complete Sudoku grid that is constructed by assigning
numbers to the locations with numbers hidden.
Here are some specifics about how this problem should be solved.
-
We assume that a Sudoku problem is given in a file, which
consists of nine lines, each consisting of nine characters,
such that the character in the file at position (i,j) (meaning row i and
column j) corresponds to the number at grid location (i,j), where the
space character represents a hidder number.
Also, each line may be shorter if the numbers are all hidden beyond
a certain point in that line.
See some input examples:
Example 1,
Example 2,
Example 3, and
Example 4.
-
The grid to be completed can be represented as a 9 by 9 array of
integers, in which 0 corresponds to a hidden number and 1 through 9
correspond to assigned numbers.
-
A hidden number can be found in the following manner using recursion:
-
For each candidate assignment, say v, for that location,
assign the value v, and check whether the puzzle can be solved
with that assignment.
-
If none of the candidate assignments do not prodiuce a solution,
then change the location back to "hidden" and return to the caller
of the method that the puzzle cannot be solved.
Two sample solutions are presented here:
a slow solution and
a fast solution.
The slow solution checks whether a number can be assigned to a location
using the aforementioned three rules and avoid trying to set an impossible
number, so as to reduce the number of recursive calls.
The fast solution adds more rules to the three and tries to find a location
for which the assingment is uniquely determined.
In both solution, a two-dimensional array of buttons is used to represent
the contents of the 9 by 9 grid. The class file for that is
Grid.java.
To show the grid on the screen you have to do:
- JFrame frame = new JFrame();
- Grid grid = new Grid(9,9);
- frame.add(grid);
- frame.pack();
- frame.setVisible(true);
The contents of the grid can be set via the following methods:
-
setDefaultColor(int i, int j): set the color of location (i,j) to green;
-
setAlternativeColor(int i, int j): set the color of location (i,j) to blue;
-
setOneText(int i, int j, String text): set the text shown at location (i,j)
to text;