07. Solve the Sudoku
The problem can be found at the following link: Question Link
My Approach
To solve the Sudoku puzzle, I have implemented a backtracking algorithm. I define a function isValid
that checks whether it's valid to place a number num
at the given cell (i, j)
on the Sudoku grid. This function checks the row, column, and the 3x3 subgrid containing the cell.
Then, I implement the SolveSudoku
function using a recursive backtracking approach. I iterate through each cell of the grid, and if the cell is empty (filled with 0
), I try placing numbers from 1
to 9
and validate if the placement is valid using the isValid
function. If valid, I proceed to the next cell and repeat the process. If a valid solution is found, the function returns true
, otherwise, I backtrack and try a different number.
Lastly, I have a printGrid
function to print the solved Sudoku grid.
Time and Auxiliary Space Complexity
Time Complexity: The backtracking algorithm explores all possible configurations of the Sudoku grid, so in the worst case, the time complexity is exponential, approximately
O(9^(N*N))
, whereN
is the size of the grid (typically 9 for standard Sudoku).Auxiliary Space Complexity: In the worst case, it can go up to
O(N*N)
, where N is the size of the grid. The additional space used for theisValid
function and temporary variables is relatively small and can be considered constant.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the getlost01/gfg-potd repository.
Last updated