Problem
Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
-
Each of the digits
1-9
must occur exactly once in each row. -
Each of the digits
1-9
must occur exactly once in each column. -
Each of the the digits
1-9
must occur exactly once in each of the 93x3
sub-boxes of the grid.
Empty cells are indicated by the character '.'
.
A sudoku puzzle…
…and its solution numbers marked in red.
Note:
-
The given board contain only digits
1-9
and the character'.'
. -
You may assume that the given Sudoku puzzle will have a single unique solution.
-
The given board size is always
9x9
.
Explanation
-
Before we start, check if the board is valid. To solve this problem, We can use backtracking, and the base case is the row is greater than 9 (index 8).
-
First, start from position
row=0, col=0
and pass it to the helper function, we need to find out the empty cell we need to fill in. Then, loop from 1 to 9, pass it to the empty cell to check if the number is valid. If it is valid, then we start from the empty cell’s next position and recursivly call the helper function. If the next position is also valid, then we finish and returntrue
. If the next position is not valid, we need to backtrack by resetting the cell to empty and iterate to the next number.
Solution
1 |
|