πDay 4. Solve the Sudoku π§
The problem can be found at the following link: Problem Link
π‘ Problem Description:
Given an incomplete Sudoku configuration in terms of a 9x9 2-D interger square matrix, mat[][], the task is to solve the Sudoku. It is guaranteed that the input Sudoku will have exactly one solution.
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.
Note: Zeros represent blanks to be filled with numbers 1-9, while non-zero cells are fixed and cannot be changed.
π Example Walkthrough:
Input: mat[][] =
Output:
Explanation: Each row, column and 3 x 3 box of the output matrix contains unique numbers.
Input: mat[][] =
Output:
Explanation: Each row, column and 3 x 3 box of the output matrix contains unique numbers.
Constraints:
mat.size() = 9mat[i].size() = 90 β€ mat[i][j] β€ 9The board is always a 9Γ9 grid.
Each row, column, and 3Γ3 sub-grid must contain digits from 1 to 9 without repetition.
π― My Approach:
Backtracking Algorithm: The problem can be efficiently solved using a backtracking approach:
Identify an empty cell.
Try placing numbers from 1 to 9 in that cell.
Check if the placement is valid (no duplicates in the row, column, or 3Γ3 sub-grid).
If valid, recursively solve the rest of the board.
If an invalid state is encountered, backtrack and try a different number.
Optimizations:
Use bitwise operations (
1 << num) to track used numbers efficiently in rows, columns, and sub-grids.Reduce redundant computations by pruning early.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(9^(n)), where
nis the number of empty cells. In the worst case, each empty cell can take one of nine values.Expected Auxiliary Space Complexity: O(1), as we modify the board in-place with constant extra storage.
π Solution Code
Code (C++)
Code (Java)
Code (Python)
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated