Problem Description
Write a program to solve a Sudoku puzzle by filling the empty cells in a 9x9 board so that every row, every column, and every 3x3 sub-box contains the digits 1 through 9 exactly once. The board input uses the '.' character to indicate empty cells, and it is guaranteed that the puzzle has only one solution.
Key Insights
- Use backtracking to explore digit placements for each empty cell.
- Validate placements by ensuring that the chosen digit is not already present in the corresponding row, column, or 3x3 sub-box.
- Employ recursion to fill the board incrementally and backtrack upon encountering invalid configurations.
- Although the worst-case time complexity is exponential, the fixed board size (9x9) keeps the problem computationally manageable.
Space and Time Complexity
Time Complexity: In the worst-case scenario, the algorithm can explore up to O(9^(n)) possibilities where n is the number of empty cells. However, since n is at most 81 and many branches are pruned early, the practical runtime is far less. Space Complexity: O(n) due to the recursion stack, where n is the number of empty cells; given the board’s fixed size, this space is constant in practice.
Solution
The solution uses a backtracking approach. For each empty cell on the board, we attempt to place a digit from '1' to '9'. Before placing a digit, we check if the placement is valid by ensuring that:
- The digit is not already present in the same row.
- The digit is not already present in the same column.
- The digit is not already present in the corresponding 3x3 sub-box.
If a valid digit is found, we place it on the board and recursively attempt to solve the rest of the board. If no valid digit can be placed, the algorithm backtracks by reverting the last move and trying a different digit. This recursive search continues until the board is completely filled with a valid Sudoku configuration.