VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sudoku-backtracking-7/

โ‡ฑ Sudoku Solver - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sudoku Solver

Last Updated : 27 Sep, 2025

Given an incomplete Sudoku in the form of matrix mat[][] of order 9*9, Complete the Sudoku.
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 in the mat[][] indicate blanks, which are to be filled with some number between 1 to 9. You can not replace the element in the cell which is not blank.

Examples:

Input:

๐Ÿ‘ Suduko-example-question

Output:

๐Ÿ‘ Suduko-example-answer

Explanation: Each row, column and 3*3 box of the output matrix contains unique numbers.

[Approach 1] Using Backtracking

The idea to solve Sudoku is to use backtracking, where we recursively try to fill the empty cells with numbers from 1 to 9. For every unassigned cell, we place a number and then check whether it is valid to place that number in the given row, column, and 3ร—3 subgrid. If it is valid, we move to the next cell; if not, we backtrack and try another number. This process continues until all cells are filled or no solution exists.


Output
3 1 6 5 7 8 4 9 2 
5 2 9 1 3 4 7 6 8 
4 8 7 6 2 9 5 3 1 
2 6 3 4 1 5 9 8 7 
9 7 4 8 6 3 1 2 5 
8 5 1 7 9 2 6 4 3 
1 3 8 9 4 7 2 5 6 
6 9 2 3 5 1 8 7 4 
7 4 5 2 8 6 3 1 9 

Time complexity: O(9(n*n)), For every unassigned index, there are 9 possible options and for each index
Auxiliary Space: O(1)

[Approach 2] Using Bit Masking with Backtracking - O(9(n*n)) Time and O(n) Space

We can solve this efficiently by using backtracking combined with bitmasking. The idea is simple: for every empty cell, we attempt to place numbers from 1 to 9 and move recursively to the next cell.

The key optimization lies in avoiding repeated scanning of the row, column, and 3ร—3 box each time we place a number. Instead, we maintain three bitmask arraysโ€”rows, cols, and boxes. In these arrays, each bit indicates whether a particular number has already been used in that row, column, or box.

Before placing a number, we simply check the corresponding bits in O(1) time to determine if it is valid. If it is safe, we set the bits and continue with recursion. If the placement leads to a dead end, we backtrack by unsetting the bits and trying another option.


Output
3 1 6 5 7 8 4 9 2 
5 2 9 1 3 4 7 6 8 
4 8 7 6 2 9 5 3 1 
2 6 3 4 1 5 9 8 7 
9 7 4 8 6 3 1 2 5 
8 5 1 7 9 2 6 4 3 
1 3 8 9 4 7 2 5 6 
6 9 2 3 5 1 8 7 4 
7 4 5 2 8 6 3 1 9 


Comment