Sodoku
Contents
Alogrithm
-
x
/**
* Input:
* vector<int> grid of size 81 (9 rows x 9 columns)
* each element contains an integer (0 to 9)
* 0 - empty cell (cell to be filled in)
* 1-9 - fixed values in a cell
*
* Output:
* input vector with 0 values filled in with values 1-9 in accordance with sodoku rules
*
* Solution:
*
* solve()
* pick the first emtpy cell starting at index 0 and incrementing by 1 to 80; call this empty cell empty_cell
*
* i = 1 -> 9
* set empty_cell to i
* if grid remains valid
* if solve()
* return grid
* else
* set empty cell to 2
*
* set empty cell to 0
*
*
* We still need to determine if the grid remains valid. A sodoku grid
* remains valid if for each cell in each row, no more than one integer in
* the integers 1 -> 9 occur (0 may occur multiple times). The same
* invariant must hold for each col and each region.
*
* Integers are introduced into the puzzle one at a time, so we only need
* to compute the validty with respect to the row, column, and region of
* the newly introduced integer. One solution is to enumerate all current
* integers in the row, column, and region that overlap with our newly
* introduced integer. Any overlapping integer must not be equal to our
* newly introduced integer.
*
* Enumerating all overlapping integers can be achieved by first finding
* all indices that overlap. The grid contains 81 cells, so for each index
* (0 -> 81) if the index overlaps, compare the value at that index to the
* newly introduced integer. If the values are equal, the grid is invalid;
* otherwise if the values are not equal continue enumerating all cells.
* After all cells are enumerated and no duplicate values are found, we
* can conclude that the grid is still valid.
* An overlapping column index occurs when the newly introduced index:
* (new_idx%9 == enum_idx%9). An overlapping row index occurs when
* (new_idx/9 == enum_idx/9).
* An overlapping region index occurs when the enum_idx is in the same 3x3
* region. We can view the regions in the grid as a 3x3 grid. Therefore,
* the enum_idx must be in the same row and column of this 3x3 grid. The
* row of idx is computed by idx/9/3 and the column by idx%9/3. So
* enum_idx overlaps the same region as new_idx when:
*
* enum_idx/9/3 == new_idx/9/3 and enum_idx%9/3 == new_idx%9/3
*
*/