Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Backtracking
  • Interview Problems on Backtracking
  • MCQs on Backtracking
  • Tutorial on Backtracking
  • Backtracking vs Recursion
  • Backtracking vs Branch & Bound
  • Print Permutations
  • Subset Sum Problem
  • N-Queen Problem
  • Knight's Tour
  • Sudoku Solver
  • Rat in Maze
  • Hamiltonian Cycle
  • Graph Coloring
Open In App
Next Article:
Magnet Puzzle
Next article icon

Algorithm to Solve Sudoku | Sudoku Solver

Last Updated : 31 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an incomplete Sudoku in the form of matrix mat[][] of order 9*9, the task is to complete the Sudoku.
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 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.

[Naive Approach] Using Backtracking

The idea is to use backtracking and recursively generate all possible configurations of numbers from 1 to 9 to fill the empty cells of matrix mat[][]. To do so, for every unassigned cell, fill the cell with a number from 1 to 9 one by one. After filling the unassigned cell check if the matrix is safe or not. If safe, move to the next cell else backtrack for other cases.

To check if it is safe to place value num in the cell mat[i][j], iterate through all the columns of row i, rows of column j and the 3*3 matrix containing cell (i, j) and check if they already has value num, if so return false, else return true.

C++
// C++ Program to solve Sudoku problem #include <iostream> #include <vector> using namespace std;  // Function to check if it is safe to place num at mat[row][col] bool isSafe(vector<vector<int>> &mat, int row, int col, int num) {      // Check if num exist in the row     for (int x = 0; x <= 8; x++)         if (mat[row][x] == num)             return false;      // Check if num exist in the col     for (int x = 0; x <= 8; x++)         if (mat[x][col] == num)             return false;      // Check if num exist in the 3x3 sub-matrix     int startRow = row - (row % 3), startCol = col - (col % 3);      for (int i = 0; i < 3; i++)         for (int j = 0; j < 3; j++)             if (mat[i + startRow][j + startCol] == num)                 return false;      return true; }  // Function to solve the Sudoku problem bool solveSudokuRec(vector<vector<int>> &mat, int row, int col) {     int n = mat.size();      // base case: Reached nth column of last row     if (row == n - 1 && col == n)         return true;      // If last column of the row go to next row     if (col == n) {         row++;         col = 0;     }      // If cell is already occupied then move forward     if (mat[row][col] != 0)         return solveSudokuRec(mat, row, col + 1);      for (int num = 1; num <= n; num++) {          // If it is safe to place num at current position         if (isSafe(mat, row, col, num)) {             mat[row][col] = num;             if (solveSudokuRec(mat, row, col + 1))                 return true;             mat[row][col] = 0;         }     }      	return false; }  void solveSudoku(vector<vector<int>> &mat) {   	solveSudokuRec(mat, 0, 0); }  int main() {     vector<vector<int>> mat = {         {3, 0, 6, 5, 0, 8, 4, 0, 0},        	{5, 2, 0, 0, 0, 0, 0, 0, 0},        	{0, 8, 7, 0, 0, 0, 0, 3, 1},         {0, 0, 3, 0, 1, 0, 0, 8, 0},        	{9, 0, 0, 8, 6, 3, 0, 0, 5},        	{0, 5, 0, 0, 9, 0, 6, 0, 0},         {1, 3, 0, 0, 0, 0, 2, 5, 0},        	{0, 0, 0, 0, 0, 0, 0, 7, 4},        	{0, 0, 5, 2, 0, 6, 3, 0, 0}};  	solveSudoku(mat);        	for (int i = 0; i < mat.size(); i++) {         for (int j = 0; j < mat.size(); j++)             cout << mat[i][j] << " ";         cout << endl;     }      return 0; } 
Java
// Java Program to solve Sudoku problem import java.util.Arrays;  class GfG {      // Function to check if it is safe to place num at mat[row][col]     static boolean isSafe(int[][] mat, int row, int col, int num) {         // Check if num exists in the row         for (int x = 0; x < 9; x++)             if (mat[row][x] == num)                 return false;          // Check if num exists in the col         for (int x = 0; x < 9; x++)             if (mat[x][col] == num)                 return false;          // Check if num exists in the 3x3 sub-matrix         int startRow = row - (row % 3), startCol = col - (col % 3);          for (int i = 0; i < 3; i++)             for (int j = 0; j < 3; j++)                 if (mat[i + startRow][j + startCol] == num)                     return false;          return true;     }      // Function to solve the Sudoku problem     static boolean solveSudokuRec(int[][] mat, int row, int col) {                // base case: Reached nth column of the last row         if (row == 8 && col == 9)             return true;          // If last column of the row go to the next row         if (col == 9) {             row++;             col = 0;         }          // If cell is already occupied then move forward         if (mat[row][col] != 0)             return solveSudokuRec(mat, row, col + 1);          for (int num = 1; num <= 9; num++) {                        // If it is safe to place num at current position             if (isSafe(mat, row, col, num)) {                 mat[row][col] = num;                 if (solveSudokuRec(mat, row, col + 1))                     return true;                 mat[row][col] = 0;             }         }          return false;     }      static void solveSudoku(int[][] mat) {         solveSudokuRec(mat, 0, 0);     }      public static void main(String[] args) {         int[][] mat = {             {3, 0, 6, 5, 0, 8, 4, 0, 0},             {5, 2, 0, 0, 0, 0, 0, 0, 0},             {0, 8, 7, 0, 0, 0, 0, 3, 1},             {0, 0, 3, 0, 1, 0, 0, 8, 0},             {9, 0, 0, 8, 6, 3, 0, 0, 5},             {0, 5, 0, 0, 9, 0, 6, 0, 0},             {1, 3, 0, 0, 0, 0, 2, 5, 0},             {0, 0, 0, 0, 0, 0, 0, 7, 4},             {0, 0, 5, 2, 0, 6, 3, 0, 0}         };          solveSudoku(mat);          for (int i = 0; i < mat.length; i++) {             for (int j = 0; j < mat[i].length; j++)                 System.out.print(mat[i][j] + " ");             System.out.println();         }     } } 
Python
# Python Program to solve Sudoku problem  # Function to check if it is safe to place num at mat[row][col] def isSafe(mat, row, col, num):     # Check if num exists in the row     for x in range(9):         if mat[row][x] == num:             return False      # Check if num exists in the col     for x in range(9):         if mat[x][col] == num:             return False      # Check if num exists in the 3x3 sub-matrix     startRow = row - (row % 3)     startCol = col - (col % 3)      for i in range(3):         for j in range(3):             if mat[i + startRow][j + startCol] == num:                 return False      return True  # Function to solve the Sudoku problem def solveSudokuRec(mat, row, col):     # base case: Reached nth column of the last row     if row == 8 and col == 9:         return True      # If last column of the row go to the next row     if col == 9:         row += 1         col = 0      # If cell is already occupied then move forward     if mat[row][col] != 0:         return solveSudokuRec(mat, row, col + 1)      for num in range(1, 10):         # If it is safe to place num at current position         if isSafe(mat, row, col, num):             mat[row][col] = num             if solveSudokuRec(mat, row, col + 1):                 return True             mat[row][col] = 0      return False  def solveSudoku(mat):     solveSudokuRec(mat, 0, 0)  if __name__ == "__main__":     mat = [         [3, 0, 6, 5, 0, 8, 4, 0, 0],         [5, 2, 0, 0, 0, 0, 0, 0, 0],         [0, 8, 7, 0, 0, 0, 0, 3, 1],         [0, 0, 3, 0, 1, 0, 0, 8, 0],         [9, 0, 0, 8, 6, 3, 0, 0, 5],         [0, 5, 0, 0, 9, 0, 6, 0, 0],         [1, 3, 0, 0, 0, 0, 2, 5, 0],         [0, 0, 0, 0, 0, 0, 0, 7, 4],         [0, 0, 5, 2, 0, 6, 3, 0, 0]     ]      solveSudoku(mat)      for row in mat:         print(" ".join(map(str, row))) 
C#
// C# Program to solve Sudoku problem  using System;  class GfG {      // Function to check if it is safe to place num at mat[row][col]     static bool isSafe(int[,] mat, int row, int col, int num) {         // Check if num exists in the row         for (int x = 0; x < 9; x++)             if (mat[row, x] == num)                 return false;          // Check if num exists in the col         for (int x = 0; x < 9; x++)             if (mat[x, col] == num)                 return false;          // Check if num exists in the 3x3 sub-matrix         int startRow = row - (row % 3), startCol = col - (col % 3);          for (int i = 0; i < 3; i++)             for (int j = 0; j < 3; j++)                 if (mat[i + startRow, j + startCol] == num)                     return false;          return true;     }      // Function to solve the Sudoku problem     static bool solveSudokuRec(int[,] mat, int row, int col) {                // base case: Reached nth column of the last row         if (row == 8 && col == 9)             return true;          // If last column of the row go to the next row         if (col == 9) {             row++;             col = 0;         }          // If cell is already occupied then move forward         if (mat[row, col] != 0)             return solveSudokuRec(mat, row, col + 1);          for (int num = 1; num <= 9; num++) {             // If it is safe to place num at current position             if (isSafe(mat, row, col, num)) {                 mat[row, col] = num;                 if (solveSudokuRec(mat, row, col + 1))                     return true;                 mat[row, col] = 0;             }         }          return false;     }      static void solveSudoku(int[,] mat) {         solveSudokuRec(mat, 0, 0);     }      public static void Main() {         int[,] mat = {             {3, 0, 6, 5, 0, 8, 4, 0, 0},             {5, 2, 0, 0, 0, 0, 0, 0, 0},             {0, 8, 7, 0, 0, 0, 0, 3, 1},             {0, 0, 3, 0, 1, 0, 0, 8, 0},             {9, 0, 0, 8, 6, 3, 0, 0, 5},             {0, 5, 0, 0, 9, 0, 6, 0, 0},             {1, 3, 0, 0, 0, 0, 2, 5, 0},             {0, 0, 0, 0, 0, 0, 0, 7, 4},             {0, 0, 5, 2, 0, 6, 3, 0, 0}         };          solveSudoku(mat);          for (int i = 0; i < 9; i++) {             for (int j = 0; j < 9; j++)                 Console.Write(mat[i, j] + " ");             Console.WriteLine();         }     } } 
JavaScript
// JavaScript Program to solve Sudoku problem  // Function to check if it is safe to place num at mat[row][col] function isSafe(mat, row, col, num) {     // Check if num exists in the row     for (let x = 0; x < 9; x++)         if (mat[row][x] === num)             return false;      // Check if num exists in the col     for (let x = 0; x < 9; x++)         if (mat[x][col] === num)             return false;      // Check if num exists in the 3x3 sub-matrix     const startRow = row - (row % 3),           startCol = col - (col % 3);      for (let i = 0; i < 3; i++)         for (let j = 0; j < 3; j++)             if (mat[i + startRow][j + startCol] === num)                 return false;      return true; }  // Function to solve the Sudoku problem function solveSudokuRec(mat, row, col) {      // base case: Reached nth column of the last row     if (row === 8 && col === 9)         return true;      // If last column of the row go to the next row     if (col === 9) {         row++;         col = 0;     }      // If cell is already occupied then move forward     if (mat[row][col] !== 0)         return solveSudokuRec(mat, row, col + 1);      for (let num = 1; num <= 9; num++) {         // If it is safe to place num at current position         if (isSafe(mat, row, col, num)) {             mat[row][col] = num;             if (solveSudokuRec(mat, row, col + 1))                 return true;             mat[row][col] = 0;         }     }      return false; }  function solveSudoku(mat) {     solveSudokuRec(mat, 0, 0); }  // Driver Code const mat = [     [3, 0, 6, 5, 0, 8, 4, 0, 0],     [5, 2, 0, 0, 0, 0, 0, 0, 0],     [0, 8, 7, 0, 0, 0, 0, 3, 1],     [0, 0, 3, 0, 1, 0, 0, 8, 0],     [9, 0, 0, 8, 6, 3, 0, 0, 5],     [0, 5, 0, 0, 9, 0, 6, 0, 0],     [1, 3, 0, 0, 0, 0, 2, 5, 0],     [0, 0, 0, 0, 0, 0, 0, 7, 4],     [0, 0, 5, 2, 0, 6, 3, 0, 0] ];  solveSudoku(mat);  mat.forEach(row => console.log(row.join(" "))); 

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(n*9(n*n)), For every unassigned index, there are 9 possible options and for each index, we are checking other columns, rows and boxes.
Auxiliary Space: O(1)

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

In the above approach, isSafe() function which is used to check if it is safe to place number num in cell (i, j) searches for num in each row, col and box. The idea is to optimize this using Bit Masking. To do so, create three arrays rows[], cols[], boxs[] of size n to mark the used value in row, column and box respectively. The element row[i] marks the number already been used in row i, and so do cols[] and boxs[] for columns and boxes. To mark the number num of row i, set the bit num from left of row[i] and operate similarly for cols[] and boxs[]. Similarly, to unmark the value num, unset the bits set in current step.

C++
// C++ Program to solve Sudoku problem #include <iostream> #include <vector> using namespace std;  // Function to heck if it is safe to place num at mat[row][col] bool isSafe(vector<vector<int>> &mat, int i, int j, int num,          vector<int> &row, vector<int> &col, vector<int> &box) {        if( (row[i] & (1 << num)) || (col[j] & (1 << num)) ||        					(box[i / 3 * 3 + j / 3] & (1 << num)) )         return false;          return true; }  bool sudokuSolverRec(vector<vector<int>> &mat, int i, int j,      		vector<int> &row, vector<int> &col, vector<int> &box) {     int n = mat.size();  	// base case: Reached nth column of last row     if (i == n - 1 && j == n)         return true;      // If reached last column of the row go to next row     if (j == n) {         i++;         j = 0;     }        // If cell is already occupied then move forward     if (mat[i][j] != 0)         return sudokuSolverRec(mat, i, j + 1, row, col, box);      for (int num = 1; num <= n; num++) {                  // If it is safe to place num at current position         if (isSafe(mat, i, j, num, row, col, box)) {             mat[i][j] = num;                      	// Update masks for the corresponding row, column and box             row[i] |= (1 << num);             col[j] |= (1 << num);             box[i / 3 * 3 + j / 3] |= (1 << num);                        if (sudokuSolverRec(mat, i, j + 1, row, col, box))                 return true;           	           	// Unmask the number num in the corresponding row, column and box masks             mat[i][j] = 0;             row[i] &= ~(1 << num);             col[j] &= ~(1 << num);             box[i / 3 * 3 + j / 3] &= ~(1 << num);         }     }        return false; }  void solveSudoku(vector<vector<int>> &mat) {   	int n = mat.size();     vector<int> row(n, 0), col(n, 0), box(n, 0);      // Set the bits in bitmasks for values that are initital present        for (int i = 0; i < n; i++) {         for (int j = 0; j < n; j++) {             if (mat[i][j] != 0) {                 row[i] |= (1 << mat[i][j]);                 col[j] |= (1 << mat[i][j]);                 box[ (i / 3) * 3 + j / 3] |= (1 << mat[i][j]);             }         }     }      sudokuSolverRec(mat, 0, 0, row, col, box); }  int main() {     vector<vector<int>> mat = {         {3, 0, 6, 5, 0, 8, 4, 0, 0},        	{5, 2, 0, 0, 0, 0, 0, 0, 0},        	{0, 8, 7, 0, 0, 0, 0, 3, 1},         {0, 0, 3, 0, 1, 0, 0, 8, 0},        	{9, 0, 0, 8, 6, 3, 0, 0, 5},        	{0, 5, 0, 0, 9, 0, 6, 0, 0},         {1, 3, 0, 0, 0, 0, 2, 5, 0},        	{0, 0, 0, 0, 0, 0, 0, 7, 4},        	{0, 0, 5, 2, 0, 6, 3, 0, 0}};  	solveSudoku(mat);        	for (int i = 0; i < mat.size(); i++) {         for (int j = 0; j < mat.size(); j++)             cout << mat[i][j] << " ";         cout << endl;     }      return 0; } 
Java
// Java Program to solve Sudoku problem import java.util.Arrays;  class GfG {      // Function to check if it is safe to place num at mat[row][col]     static boolean isSafe(int[][] mat, int i, int j, int num,                            int[] row, int[] col, int[] box) {         if ((row[i] & (1 << num)) != 0 || (col[j] & (1 << num)) != 0 ||              (box[i / 3 * 3 + j / 3] & (1 << num)) != 0)             return false;                  return true;     }      static boolean sudokuSolverRec(int[][] mat, int i, int j,                                     int[] row, int[] col, int[] box) {         int n = mat.length;          // base case: Reached nth column of last row         if (i == n - 1 && j == n)             return true;          // If reached last column of the row go to next row         if (j == n) {             i++;             j = 0;         }          // If cell is already occupied then move forward         if (mat[i][j] != 0)             return sudokuSolverRec(mat, i, j + 1, row, col, box);          for (int num = 1; num <= n; num++) {             // If it is safe to place num at current position             if (isSafe(mat, i, j, num, row, col, box)) {                 mat[i][j] = num;                  // Update masks for the corresponding row, column and box                 row[i] |= (1 << num);                 col[j] |= (1 << num);                 box[i / 3 * 3 + j / 3] |= (1 << num);                  if (sudokuSolverRec(mat, i, j + 1, row, col, box))                     return true;                  // Unmask the number num in the corresponding row, column and box masks                 mat[i][j] = 0;                 row[i] &= ~(1 << num);                 col[j] &= ~(1 << num);                 box[i / 3 * 3 + j / 3] &= ~(1 << num);             }         }          return false;     }      static void solveSudoku(int[][] mat) {         int n = mat.length;         int[] row = new int[n];         int[] col = new int[n];         int[] box = new int[n];          // Set the bits in bitmasks for values that are initially present         for (int i = 0; i < n; i++) {             for (int j = 0; j < n; j++) {                 if (mat[i][j] != 0) {                     row[i] |= (1 << mat[i][j]);                     col[j] |= (1 << mat[i][j]);                     box[(i / 3) * 3 + j / 3] |= (1 << mat[i][j]);                 }             }         }          sudokuSolverRec(mat, 0, 0, row, col, box);     }      public static void main(String[] args) {         int[][] mat = {             {3, 0, 6, 5, 0, 8, 4, 0, 0},             {5, 2, 0, 0, 0, 0, 0, 0, 0},             {0, 8, 7, 0, 0, 0, 0, 3, 1},             {0, 0, 3, 0, 1, 0, 0, 8, 0},             {9, 0, 0, 8, 6, 3, 0, 0, 5},             {0, 5, 0, 0, 9, 0, 6, 0, 0},             {1, 3, 0, 0, 0, 0, 2, 5, 0},             {0, 0, 0, 0, 0, 0, 0, 7, 4},             {0, 0, 5, 2, 0, 6, 3, 0, 0}         };          solveSudoku(mat);          for (int i = 0; i < mat.length; i++) {             for (int j = 0; j < mat[i].length; j++)                 System.out.print(mat[i][j] + " ");             System.out.println();         }     } } 
Python
# Python Program to solve Sudoku problem  def isSafe(mat, i, j, num, row, col, box):     if (row[i] & (1 << num)) or (col[j] & (1 << num)) or (box[i // 3 * 3 + j // 3] & (1 << num)):         return False     return True  def sudokuSolverRec(mat, i, j, row, col, box):     n = len(mat)      # base case: Reached nth column of last row     if i == n - 1 and j == n:         return True      # If reached last column of the row go to next row     if j == n:         i += 1         j = 0      # If cell is already occupied then move forward     if mat[i][j] != 0:         return sudokuSolverRec(mat, i, j + 1, row, col, box)      for num in range(1, n + 1):         # If it is safe to place num at current position         if isSafe(mat, i, j, num, row, col, box):             mat[i][j] = num              # Update masks for the corresponding row, column and box             row[i] |= (1 << num)             col[j] |= (1 << num)             box[i // 3 * 3 + j // 3] |= (1 << num)              if sudokuSolverRec(mat, i, j + 1, row, col, box):                 return True              # Unmask the number num in the corresponding row, column and box masks             mat[i][j] = 0             row[i] &= ~(1 << num)             col[j] &= ~(1 << num)             box[i // 3 * 3 + j // 3] &= ~(1 << num)      return False  def solveSudoku(mat):     n = len(mat)     row = [0] * n     col = [0] * n     box = [0] * n      # Set the bits in bitmasks for values that are initially present     for i in range(n):         for j in range(n):             if mat[i][j] != 0:                 row[i] |= (1 << mat[i][j])                 col[j] |= (1 << mat[i][j])                 box[(i // 3) * 3 + j // 3] |= (1 << mat[i][j])      sudokuSolverRec(mat, 0, 0, row, col, box)  if __name__ == "__main__":     mat = [         [3, 0, 6, 5, 0, 8, 4, 0, 0],         [5, 2, 0, 0, 0, 0, 0, 0, 0],         [0, 8, 7, 0, 0, 0, 0, 3, 1],         [0, 0, 3, 0, 1, 0, 0, 8, 0],         [9, 0, 0, 8, 6, 3, 0, 0, 5],         [0, 5, 0, 0, 9, 0, 6, 0, 0],         [1, 3, 0, 0, 0, 0, 2, 5, 0],         [0, 0, 0, 0, 0, 0, 0, 7, 4],         [0, 0, 5, 2, 0, 6, 3, 0, 0]     ]      solveSudoku(mat)      for row in mat:         print(" ".join(map(str, row))) 
C#
// C# Program to solve Sudoku problem using bitmasks using System;  class GfG {      // Function to check if it is safe to place num at mat[row, col]     static bool isSafe(int[,] mat, int i, int j, int num,                         	int[] row, int[] col, int[] box) {                if ((row[i] & (1 << num)) != 0 || (col[j] & (1 << num)) != 0 ||             (box[i / 3 * 3 + j / 3] & (1 << num)) != 0)             return false;          return true;     }      static bool sudokuSolverRec(int[,] mat, int i, int j,                                  int[] row, int[] col, int[] box) {         int n = mat.GetLength(0);          // base case: Reached nth column of last row         if (i == n - 1 && j == n)             return true;          // If reached last column of the row, go to next row         if (j == n) {             i++;             j = 0;         }          // If cell is already occupied, then move forward         if (mat[i, j] != 0)             return sudokuSolverRec(mat, i, j + 1, row, col, box);          for (int num = 1; num <= n; num++) {              // If it is safe to place num at current position             if (isSafe(mat, i, j, num, row, col, box)) {                 mat[i, j] = num;                  // Update masks for the corresponding row, column, and box                 row[i] |= (1 << num);                 col[j] |= (1 << num);                 box[i / 3 * 3 + j / 3] |= (1 << num);                  if (sudokuSolverRec(mat, i, j + 1, row, col, box))                     return true;                  // Unmask the number num in the corresponding row, column and box masks                 mat[i, j] = 0;                 row[i] &= ~(1 << num);                 col[j] &= ~(1 << num);                 box[i / 3 * 3 + j / 3] &= ~(1 << num);             }         }          return false;     }      static void solveSudoku(int[,] mat) {         int n = mat.GetLength(0);         int[] row = new int[n];         int[] col = new int[n];         int[] box = new int[n];          // Set the bits in bitmasks for values that are initially present         for (int i = 0; i < n; i++) {             for (int j = 0; j < n; j++) {                 if (mat[i, j] != 0) {                     row[i] |= (1 << mat[i, j]);                     col[j] |= (1 << mat[i, j]);                     box[(i / 3) * 3 + j / 3] |= (1 << mat[i, j]);                 }             }         }          sudokuSolverRec(mat, 0, 0, row, col, box);     }      public static void Main(string[] args) {         int[,] mat = {             {3, 0, 6, 5, 0, 8, 4, 0, 0},             {5, 2, 0, 0, 0, 0, 0, 0, 0},             {0, 8, 7, 0, 0, 0, 0, 3, 1},             {0, 0, 3, 0, 1, 0, 0, 8, 0},             {9, 0, 0, 8, 6, 3, 0, 0, 5},             {0, 5, 0, 0, 9, 0, 6, 0, 0},             {1, 3, 0, 0, 0, 0, 2, 5, 0},             {0, 0, 0, 0, 0, 0, 0, 7, 4},             {0, 0, 5, 2, 0, 6, 3, 0, 0}         };          solveSudoku(mat);          for (int i = 0; i < mat.GetLength(0); i++) {             for (int j = 0; j < mat.GetLength(1); j++)                 Console.Write(mat[i, j] + " ");             Console.WriteLine();         }     } } 
JavaScript
// JavaScript Program to solve Sudoku problem using bitmasks  // Function to check if it is safe to place num at mat[row][col] function isSafe(mat, i, j, num, row, col, box) {     if ((row[i] & (1 << num)) !== 0 || (col[j] & (1 << num)) !== 0 ||         (box[Math.floor(i / 3) * 3 + Math.floor(j / 3)] & (1 << num)) !== 0)         return false;      return true; }  function sudokuSolverRec(mat, i, j, row, col, box) {     const n = mat.length;      // base case: Reached nth column of last row     if (i === n - 1 && j === n)         return true;      // If reached last column of the row, go to next row     if (j === n) {         i++;         j = 0;     }      // If cell is already occupied, then move forward     if (mat[i][j] !== 0)         return sudokuSolverRec(mat, i, j + 1, row, col, box);      for (let num = 1; num <= n; num++) {          // If it is safe to place num at current position         if (isSafe(mat, i, j, num, row, col, box)) {             mat[i][j] = num;              // Update masks for the corresponding row, column, and box             row[i] |= (1 << num);             col[j] |= (1 << num);             box[Math.floor(i / 3) * 3 + Math.floor(j / 3)] |= (1 << num);              if (sudokuSolverRec(mat, i, j + 1, row, col, box))                 return true;              // Unmask the number num in the corresponding row, column and box masks             mat[i][j] = 0;             row[i] &= ~(1 << num);             col[j] &= ~(1 << num);             box[Math.floor(i / 3) * 3 + Math.floor(j / 3)] &= ~(1 << num);         }     }      return false; }  function solveSudoku(mat) {     const n = mat.length;     const row = new Array(n).fill(0);     const col = new Array(n).fill(0);     const box = new Array(n).fill(0);      // Set the bits in bitmasks for values that are initially present     for (let i = 0; i < n; i++) {         for (let j = 0; j < n; j++) {             if (mat[i][j] !== 0) {                 row[i] |= (1 << mat[i][j]);                 col[j] |= (1 << mat[i][j]);                 box[Math.floor(i / 3) * 3 + Math.floor(j / 3)] |= (1 << mat[i][j]);             }         }     }      sudokuSolverRec(mat, 0, 0, row, col, box); }  // Driver Code const mat = [     [3, 0, 6, 5, 0, 8, 4, 0, 0],     [5, 2, 0, 0, 0, 0, 0, 0, 0],     [0, 8, 7, 0, 0, 0, 0, 3, 1],     [0, 0, 3, 0, 1, 0, 0, 8, 0],     [9, 0, 0, 8, 6, 3, 0, 0, 5],     [0, 5, 0, 0, 9, 0, 6, 0, 0],     [1, 3, 0, 0, 0, 0, 2, 5, 0],     [0, 0, 0, 0, 0, 0, 0, 7, 4],     [0, 0, 5, 2, 0, 6, 3, 0, 0] ];  solveSudoku(mat);  for (let i = 0; i < mat.length; i++) {     console.log(mat[i].join(" ")); } 

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))
Auxiliary Space: O(n)




Next Article
Magnet Puzzle
author
kartik
Improve
Article Tags :
  • Backtracking
  • DSA
  • Matrix
  • Amazon
  • Directi
  • Flipkart
  • Google
  • MakeMyTrip
  • MAQ Software
  • Microsoft
  • Ola Cabs
  • Oracle
  • PayPal
  • Zoho
Practice Tags :
  • Amazon
  • Directi
  • Flipkart
  • Google
  • MakeMyTrip
  • MAQ Software
  • Microsoft
  • Ola Cabs
  • Oracle
  • PayPal
  • Zoho
  • Backtracking
  • Matrix

Similar Reads

  • Backtracking Algorithm
    Backtracking algorithms are like problem-solving strategies that help explore different options to find the best solution. They work by trying out different paths and if one doesn't work, they backtrack and try another until they find the right one. It's like solving a puzzle by testing different pi
    4 min read
  • Introduction to Backtracking
    Backtracking is like trying different paths, and when you hit a dead end, you backtrack to the last choice and try a different route. In this article, we'll explore the basics of backtracking, how it works, and how it can help solve all sorts of challenging problems. It's like a method for finding t
    7 min read
  • Difference between Backtracking and Branch-N-Bound technique
    Algorithms are the methodical sequence of steps which are defined to solve complex problems. In this article, we will see the difference between two such algorithms which are backtracking and branch and bound technique. Before getting into the differences, lets first understand each of these algorit
    4 min read
  • What is the difference between Backtracking and Recursion?
    What is Recursion?The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Real Life ExampleImagine we have a set of boxes, each containing a smaller box. To find an item, we open the outermost box and cont
    4 min read
  • Standard problems on backtracking

    • The Knight's tour problem
      Given an n × n chessboard with a Knight starting at the top-left corner (position (0, 0)). The task is to determine a valid Knight's Tour where where the Knight visits each cell exactly once following the standard L-shaped moves of a Knight in chess.If a valid tour exists, print an n × n grid where
      15+ min read

    • Rat in a Maze
      Given an n x n binary matrix representing a maze, where 1 means open and 0 means blocked, a rat starts at (0, 0) and needs to reach (n - 1, n - 1). The rat can move up (U), down (D), left (L), and right (R), but: It cannot visit the same cell more than once.It can only move through cells with value
      9 min read

    • N Queen Problem
      Given an integer n, the task is to find the solution to the n-queens problem, where n queens are placed on an n*n chessboard such that no two queens can attack each other. The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example,
      15+ min read

    • Subset Sum Problem using Backtracking
      Given a set[] of non-negative integers and a value sum, the task is to print the subset of the given set whose sum is equal to the given sum. Examples:  Input: set[] = {1,2,1}, sum = 3Output: [1,2],[2,1]Explanation: There are subsets [1,2],[2,1] with sum 3. Input: set[] = {3, 34, 4, 12, 5, 2}, sum =
      8 min read

    • M-Coloring Problem
      Given an edges of graph and a number m, the your task is to find weather is possible to color the given graph with at most m colors such that no two adjacent vertices of the graph are colored with the same color. Examples Input: V = 4, edges[][] = [[0, 1], [0, 2], [0,3], [1, 3], [2, 3]], m = 3Output
      13 min read

    • Hamiltonian Cycle
      What is Hamiltonian Cycle?Hamiltonian Cycle or Circuit in a graph G is a cycle that visits every vertex of G exactly once and returns to the starting vertex. If graph contains a Hamiltonian cycle, it is called Hamiltonian graph otherwise it is non-Hamiltonian.Finding a Hamiltonian Cycle in a graph i
      15+ min read

    • Algorithm to Solve Sudoku | Sudoku Solver
      Given an incomplete Sudoku in the form of matrix mat[][] of order 9*9, the task is to 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 di
      15+ min read

    • Magnet Puzzle
      The puzzle game Magnets involves placing a set of domino-shaped magnets (or electrets or other polarized objects) in a subset of slots on a board so as to satisfy a set of constraints. For example, the puzzle on the left has the solution shown on the right:   Each slot contains either a blank entry
      15+ min read

    • Remove Invalid Parentheses
      Given a string str consisting only of lowercase letters and the characters '(' and ')'. Your task is to delete minimum parentheses so that the resulting string is balanced, i.e., every opening parenthesis has a matching closing parenthesis in the correct order, and no extra closing parentheses appea
      15+ min read

    • A backtracking approach to generate n bit Gray Codes
      Given a number n, the task is to generate n bit Gray codes (generate bit patterns from 0 to 2^n-1 such that successive patterns differ by one bit) Examples: Input : 2 Output : 0 1 3 2Explanation : 00 - 001 - 111 - 310 - 2Input : 3 Output : 0 1 3 2 6 7 5 4 We have discussed an approach in Generate n-
      6 min read

    • Permutations of given String
      Given a string s, the task is to return all permutations of a given string in lexicographically sorted order. Note: A permutation is the rearrangement of all the elements of a string. Duplicate arrangement can exist. Examples: Input: s = "ABC"Output: "ABC", "ACB", "BAC", "BCA", "CAB", "CBA" Input: s
      5 min read

    Easy Problems on Backtracking

    • Print all subsets of a given Set or Array
      Given an array arr of size n, your task is to print all the subsets of the array in lexicographical order. A subset is any selection of elements from an array, where the order does not matter, and no element appears more than once. It can include any number of elements, from none (the empty subset)
      12 min read

    • Check if a given string is sum-string
      Given a string of digits, determine whether it is a ‘sum-string’. A string S is called a sum-string if the rightmost substring can be written as the sum of two substrings before it and the same is recursively true for substrings before it. Examples: “12243660” is a sum string. Explanation : 24 + 36
      12 min read

    • Count all possible Paths between two Vertices
      Count the total number of ways or paths that exist between two vertices in a directed graph. These paths don't contain a cycle, the simple enough reason is that a cycle contains an infinite number of paths and hence they create a problem Examples: For the following Graph: Input: Count paths between
      9 min read

    • Find all distinct subsets of a given set using BitMasking Approach
      Given an array of integers arr[], The task is to find all its subsets. The subset can not contain duplicate elements, so any repeated subset should be considered only once in the output. Examples: Input: S = {1, 2, 2}Output: {}, {1}, {2}, {1, 2}, {2, 2}, {1, 2, 2}Explanation: The total subsets of gi
      12 min read

    • Find if there is a path of more than k weight from a source
      Given an undirected graph represented by the edgeList[][], where each edgeList[i] contains three integers [u, v, w], representing an undirected edge from u to v, having distance w. You are also given a source vertex, and a positive integer k. Your task is to determine if there exist a simple path (w
      10 min read

    • Print all paths from a given source to a destination
      Given a directed acyclic graph, a source vertex src and a destination vertex dest, print all paths from given src to dest. Examples: Input: V = 4, edges[ ][ ] = [[0, 1], [1, 2], [1, 3], [2, 3]], src = 0, dest = 3Output: [[0, 1, 2, 3], [0, 1, 3]]Explanation: There are two ways to reach at 3 from 0. T
      12 min read

    • Print all possible strings that can be made by placing spaces
      Given a string you need to print all possible strings that can be made by placing spaces (zero or one) in between them. Input: str[] = "ABC" Output: ABC AB C A BC A B C Source: Amazon Interview Experience | Set 158, Round 1, Q 1. Recommended PracticePermutation with SpacesTry It! The idea is to use
      11 min read

    Medium prblems on Backtracking

    • Tug of War
      Given a set of n integers, divide the set in two subsets of n/2 sizes each such that the absolute difference of the sum of two subsets is as minimum as possible. If n is even, then sizes of two subsets must be strictly n/2 and if n is odd, then size of one subset must be (n-1)/2 and size of other su
      15 min read

    • 8 queen problem
      The eight queens problem is the problem of placing eight queens on an 8×8 chessboard such that none of them attack one another (no two are in the same row, column, or diagonal). More generally, the n queens problem places n queens on an n×n chessboard. There are different solutions for the problem.
      8 min read

    • Combination Sum
      Given an array of distinct integers arr[] and an integer target, the task is to find a list of all unique combinations of array where the sum of chosen element is equal to target. Note: The same number may be chosen from array an unlimited number of times. Two combinations are unique if the frequenc
      8 min read

    • Warnsdorff's algorithm for Knight’s tour problem
      Problem : A knight is placed on the first block of an empty board and, moving according to the rules of chess, must visit each square exactly once. Following is an example path followed by Knight to cover all the cells. The below grid represents a chessboard with 8 x 8 cells. Numbers in cells indica
      15+ min read

    • Find paths from corner cell to middle cell in maze
      Given a square maze represented by a matrix mat[][] of positive numbers, the task is to find all paths from all four corner cells to the middle cell. From any cell mat[i][j] with value n, you are allowed to move exactly n steps in one of the four cardinal directions—North, South, East, or West. That
      14 min read

    • Maximum number possible by doing at-most K swaps
      Given a string s and an integer k, the task is to find the maximum possible number by performing swap operations on the digits of s at most k times. Examples: Input: s = "7599", k = 2Output: 9975Explanation: Two Swaps can make input 7599 to 9975. First swap 9 with 5 so number becomes 7995, then swap
      15 min read

    • Rat in a Maze with multiple steps or jump allowed
      You are given an n × n maze represented as a matrix. The rat starts from the top-left corner (mat[0][0]) and must reach the bottom-right corner (mat[n-1][n-1]). The rat can move forward (right) or downward.A 0 in the matrix represents a dead end, meaning the rat cannot step on that cell.A non-zero v
      11 min read

    • N Queen in O(n) space
      Given an integer n, the task is to find the solution to the n-queens problem, where n queens are placed on an n*n chessboard such that no two queens can attack each other. The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example,
      7 min read

    Hard problems on Backtracking

    • Power Set in Lexicographic order
      This article is about generating Power set in lexicographical order. Examples : Input : abcOutput : a ab abc ac b bc cThe idea is to sort array first. After sorting, one by one fix characters and recursively generates all subsets starting from them. After every recursive call, we remove last charact
      9 min read

    • Word Break Problem using Backtracking
      Given a non-empty sequence s and a dictionary dict[] containing a list of non-empty words, the task is to return all possible ways to break the sentence in individual dictionary words.Note: The same word in the dictionary may be reused multiple times while breaking.Examples: Input: s = “catsanddog”
      8 min read

    • Partition of a set into K subsets with equal sum
      Given an integer array arr[] and an integer k, the task is to check if it is possible to divide the given array into k non-empty subsets of equal sum such that every array element is part of a single subset. Examples: Input: arr[] = [2, 1, 4, 5, 6], k = 3 Output: trueExplanation: Possible subsets of
      9 min read

    • Longest Possible Route in a Matrix with Hurdles
      Given an M x N matrix, with a few hurdles arbitrarily placed, calculate the length of the longest possible route possible from source to a destination within the matrix. We are allowed to move to only adjacent cells which are not hurdles. The route cannot contain any diagonal moves and a location on
      15+ min read

    • Find shortest safe route in a path with landmines
      Given a path in the form of a rectangular matrix having few landmines arbitrarily placed (marked as 0), calculate length of the shortest safe route possible from any cell in the first column to any cell in the last column of the matrix. We have to avoid landmines and their four adjacent cells (left,
      15+ min read

    • Printing all solutions in N-Queen Problem
      Given an integer n, the task is to find all distinct solutions to the n-queens problem, where n queens are placed on an n * n chessboard such that no two queens can attack each other. Note: Each solution is a unique configuration of n queens, represented as a permutation of [1,2,3,....,n]. The numbe
      15+ min read

    • Print all longest common sub-sequences in lexicographical order
      You are given two strings, the task is to print all the longest common sub-sequences in lexicographical order. Examples: Input : str1 = "abcabcaa", str2 = "acbacba" Output: ababa abaca abcba acaba acaca acbaa acbcaRecommended PracticePrint all LCS sequencesTry It! This problem is an extension of lon
      14 min read

  • Top 20 Backtracking Algorithm Interview Questions
    Backtracking is a powerful algorithmic technique used to solve problems by exploring all possible solutions in a systematic and recursive manner. It is particularly useful for problems that require searching through a vast solution space, such as combinatorial problems, constraint satisfaction probl
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences