Thursday, October 8, 2015

Sudoku Solver

I have implemented a basic version of Sudoku solver. Though you can solve Sudoku by backtracking, I implemented with several logics.

Step 1: Find all possible values for all unsolved cells.
Step 2: For each unsolved cell, if it has only one possible value, then mark it as solved.
Step 2.1: Remove the previously solved value from possible values of following cells.
*) All unsolved cells in current square.
*) All unsolved cells in current row.
*) All unsolved cells in current column.
Step 3: For each row, if a value possible in only one cell, then mark it as solved.
(Eg., if 1st row 5th cell has possible values 1,7,9. But in 1st row the value 7 is possible only in 5th cell's, then place 7 in 1st row 5th cell, and mark it as solved).
Setp 3.1: Do step 2.1.
Step 4: Do step 3 for column followed by do step 2.1.
Step 5: Do step 3 for square followed by do step 2.1.
Step 6: For each row, any n  (where n < 9) cells, find union of possible values of n cells say U. If size of U = n, then remove those values from all other unsolved cells in the current row.
(Eg., if 1st row 5th cell has possible values 6, 7  & 8, and 6th cell has possible value 6 & 7 alone and 9 the cell has 6, 7 & 8. Then U = {6, 7, 8}. Size of U is 3 and n = 3 ( because 3 cells 5, 6 & 9 selected). Size of U = n, so remove 6, 7 and 8 from all unsolved cell's possible value in the current row).
Step 7: Do step 6 for column.
Step 8: Do step 6 for cell.
Step 9: If there was any change happened (like solved or change happened in possible values of any cell), then go to Step 2.
Step 10: Filled maximum possible steps.

This is how I solved