πŸš€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:

  1. Each of the digits 1-9 must occur exactly once in each row.

  2. Each of the digits 1-9 must occur exactly once in each column.

  3. 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() = 9

  • mat[i].size() = 9

  • 0 ≀ mat[i][j] ≀ 9

  • The 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:

  1. 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.

  2. 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 n is 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