Since one of the trickier parts is determining a 3x3 square, here's the method I use to determine the 3x3 square in a standard Sudoku (note that this method can also be adapted for different sized Sudokus). You'll also probably want separate functions to check rows, columns, and 3x3 squares for a value instead of one possible() function as it's easier to error check and is more readable imo.
---
It is possible to determine where a 3x3 square begins and ends given a specific position on the Sudoku. Labelling the rows 0-8 starting from the top and the columns 0-8 starting from the left, then labelling the 3x3 squares 0-8 with 0 at the upper left and 8 at the lower right gives the following square numbers:
000111222
000111222
000111222
333444555
333444555
333444555
666777888
666777888
666777888
Now consider the position (1,7), marked by an *:
000111222
0001112*2
000111222
333444555
333444555
333444555
666777888
666777888
666777888
It lies in square 2. There are multiple ways to determine where the 3x3 square begins and ends given the position, but it would be best that, given ANY position, you could determine the upperleft position of the 3x3 square containing the position in question. For example given * we want to find U:
---initial example---
000111U22
0001112*2
000111222
333444555
333444555
333444555
666777888
666777888
666777888
---another example---
000U11222
000111222
000*11222
333444555
333444555
333444555
666777888
666777888
666777888
---one more example---
000111222
000111222
000111222
333444555
333444555
333444555
666*77888 (U is the same position as *)
666777888
666777888
Once you have determined U, the 3 rows of the 3x3 square are (U's row) to (U's row)+2 and the 3 columns are (U's column) to (U's column)+2. By determining U from any arbitrary position, the need to label the squares is eliminated as well. First try to figure out how to determine U yourself, but if you have trouble or it seems extremely difficult read the following code below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
//square_top() returns either the upmost row of the 3x3 square at row "num" or the leftmost column at column "num".
//the algorithm is the same for both rows and columns so it doesn't make a difference whether "num" represents a row
//or a column.
int square_top(int num);
.
.
.
.
int square_top(int num)
{
if (num % 3 == 0)
return num;
if (num % 3 == 1)
return num - 1;
return num - 2;
}
|