Write a program to solve a Sudoku puzzle by filling in the empty cells (represented as '.'). A valid Sudoku solution must satisfy: each row contains digits 1–9 without repetition, each column contains digits 1–9 without repetition, and each of the nine 3x3 sub-boxes contains digits 1–9 without repetition.
Output: The board is filled in-place with the unique valid solution.
Output: The board is solved in-place.
We scan the board cell by cell. When we find an empty cell ('.') we try digits '1' through '9'. For each candidate we check if it is valid for the current row, column, and 3x3 box. If valid, we place it and recurse. If the recursion returns false (no solution found), we reset the cell and try the next digit.
- The
solvemethod scans left-to-right, top-to-bottom for empty cells. - If no empty cell is found, the board is fully solved — return true.
- The
isValidhelper checks the row, column, and 3x3 box for the candidate digit. - Backtrack by resetting the cell to
'.'when no digit leads to a solution.
Complexity Analysis:
Time complexity: O(9^m) where m is the number of empty cells — at most 9 choices per cell.
Space complexity: O(m) for the recursion stack.