Sudoku Solver
Last updated
Last updated
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 digits 1-9
must occur exactly once in each of the 9 3x3
sub-boxes of the grid.
The '.'
character indicates empty cells.
Example 1:
Constraints:
board.length == 9
board[i].length == 9
board[i][j]
is a digit or '.'
.
It is guaranteed that the input board has only one solution.
This problem can be solved using backtracking, which is a common technique for solving constraint satisfaction problems like Sudoku. The idea is to fill the cells one by one, and whenever we find that current cell cannot lead to a solution, we empty the cell (backtrack) and move on to the next cell.
In this code, Solve
is a recursive function that tries to fill the cells from top to bottom and left to right. For each empty cell, it tries all possible numbers from 1 to 9, and calls itself to fill the next cell. If it finds that the current cell cannot lead to a solution (no valid numbers can be placed or the recursive call returns false), it empties the cell (backtracks) and continues with the next number. If it has tried all numbers and none of them work, it returns false to backtrack to the previous cell. The process continues until all cells are filled.
IsValid
is a helper function that checks if a number can be placed in a certain cell according to the Sudoku rules.
The time complexity of this solution is O(9^(nn)), where n is the number of empty cells, because in the worst case we need to try 9 numbers for each empty cell. The space complexity is O(nn) because of the recursion stack (depth-first search).