Tutorialspoint
Problem
Solution
Submissions

Sudoku Solver

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program to solve a Sudoku puzzle using backtracking. A Sudoku puzzle is a 9×9 grid where some cells are filled with digits 1-9, and the goal is to fill the remaining empty cells. The rules are: each row, column, and 3×3 sub-box must contain all digits from 1 to 9 exactly once.

Example 1
  • Input: 9x9 Sudoku grid with some filled cells and empty cells (represented by 0)
  • Output: Solved Sudoku
  • Explanation:
    • Fill empty cells (represented by 0) following Sudoku rules.
    • Each row, column, and 3×3 box must contain digits 1-9 exactly once.
    • Use backtracking to try different possibilities and find the solution.
Example 2
  • Input: Invalid Sudoku (no solution)
  • Output: "No solution exists"
  • Explanation:
    • Some Sudoku puzzles may not have a valid solution.
    • The algorithm will try all possibilities and determine no solution exists.
    • Return appropriate message indicating unsolvable puzzle.
Constraints
  • The Sudoku grid is always 9×9
  • Empty cells are represented by 0
  • Given digits are between 1-9
  • There is at most one unique solution
  • Time Complexity: O(9^(n*n)) in worst case where n=9
  • Space Complexity: O(n*n) for recursion stack
Backtracking Goldman SachsTutorix
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use backtracking algorithm to try filling each empty cell with digits 1-9
  • For each empty cell, check if placing a digit is valid according to Sudoku rules
  • A digit is valid if it doesn't appear in the same row, column, or 3×3 sub-box
  • If a digit placement leads to a solution, continue; otherwise backtrack and try next digit
  • Use helper functions to check row, column, and box validity separately
  • Find empty cells systematically and fill them one by one

Steps to solve by this approach:

 Step 1: Find the first empty cell (containing 0) in the Sudoku grid
 Step 2: Try placing digits 1 through 9 in the empty cell
 Step 3: For each digit, check if placement is valid by verifying row, column, and 3×3 box constraints
 Step 4: If placement is valid, place the digit and recursively solve the remaining puzzle
 Step 5: If recursive call returns true, the puzzle is solved; if false, backtrack by removing the digit
 Step 6: If no digit (1-9) works for current cell, return false to trigger backtracking
 Step 7: If no empty cells remain, the puzzle is completely solved and return true

Submitted Code :