codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🧮

Data Structures & Algorithms

38 / 65 topics
36Backtracking Basics37N-Queens Problem38Sudoku Solver39Maze Solving using Backtracking
Tutorials/Data Structures & Algorithms/Sudoku Solver
🧮Data Structures & Algorithms

Sudoku Solver

Updated 2026-04-20
3 min read

Sudoku Solver

Introduction

Sudoku is a popular number-placement puzzle where the objective is to fill a 9x9 grid with digits so that each column, each row, and each of the nine 3x3 subgrids (also known as "boxes") contains all of the digits from 1 to 9. The puzzle starts with some cells already filled in, and the player must fill in the remaining cells.

In this tutorial, we will explore how to solve a Sudoku puzzle using the backtracking algorithm. Backtracking is a powerful technique used in computer science for solving constraint satisfaction problems by incrementally building candidates and abandoning a candidate as soon as it determines that the candidate cannot possibly be completed to a valid solution.

Understanding the Problem

Before diving into the implementation, let's break down the problem:

  1. Grid Representation: The Sudoku grid is a 9x9 matrix.
  2. Constraints:
    • Each row must contain all digits from 1 to 9 without repetition.
    • Each column must contain all digits from 1 to 9 without repetition.
    • Each of the nine 3x3 subgrids must contain all digits from 1 to 9 without repetition.

Backtracking Algorithm

Backtracking is a recursive algorithm that attempts to build a solution incrementally, one piece at a time. If it determines that the current path cannot lead to a valid solution, it backtracks and tries a different path.

Steps for Sudoku Solver using Backtracking:

  1. Find an Empty Cell: Start by finding an empty cell in the grid (a cell with value 0).
  2. Try Digits 1-9: For each empty cell, try placing digits from 1 to 9.
  3. Check Validity: Check if placing a digit violates any Sudoku constraints.
  4. Recursive Call: If valid, recursively attempt to solve the rest of the grid.
  5. Backtrack: If placing a digit leads to an invalid state or cannot complete the puzzle, backtrack and try the next digit.

Base Case

The base case for the recursion is when there are no more empty cells left in the grid, indicating that the puzzle has been solved successfully.

Implementation

Let's implement the Sudoku solver using backtracking in Python. We'll use a 2D list to represent the Sudoku grid.

def is_valid(board, row, col, num):
    # Check if 'num' is not in the current row
    for x in range(9):
        if board[row][x] == num:
            return False

    # Check if 'num' is not in the current column
    for x in range(9):
        if board[x][col] == num:
            return False

    # Check if 'num' is not in the current 3x3 subgrid
    start_row = row - row % 3
    start_col = col - col % 3
    for i in range(3):
        for j in range(3):
            if board[i + start_row][j + start_col] == num:
                return False

    return True

def solve_sudoku(board):
    empty = find_empty_location(board)
    if not empty:
        return True  # Puzzle solved
    row, col = empty

    for num in range(1, 10):
        if is_valid(board, row, col, num):
            board[row][col] = num

            if solve_sudoku(board):
                return True

            board[row][col] = 0  # Backtrack

    return False

def find_empty_location(board):
    for i in range(9):
        for j in range(9):
            if board[i][j] == 0:
                return (i, j)
    return None

# Example usage
sudoku_board = [
    [5, 3, 0, 0, 7, 0, 0, 0, 0],
    [6, 0, 0, 1, 9, 5, 0, 0, 0],
    [0, 9, 8, 0, 0, 0, 0, 6, 0],
    [8, 0, 0, 0, 6, 0, 0, 0, 3],
    [4, 0, 0, 8, 0, 3, 0, 0, 1],
    [7, 0, 0, 0, 2, 0, 0, 0, 6],
    [0, 6, 0, 0, 0, 0, 2, 8, 0],
    [0, 0, 0, 4, 1, 9, 0, 0, 5],
    [0, 0, 0, 0, 8, 0, 0, 7, 9]
]

if solve_sudoku(sudoku_board):
    print("Sudoku solved successfully!")
else:
    print("No solution exists.")

# Print the solved Sudoku board
for row in sudoku_board:
    print(row)

Explanation of the Code

  1. is_valid Function: This function checks if placing a number at a specific cell is valid according to Sudoku rules.
  2. solve_sudoku Function: This is the main recursive function that attempts to solve the Sudoku puzzle.
  3. find_empty_location Function: This helper function finds an empty cell in the grid.

Key Points

  • Backtracking: The algorithm tries each possible number and backtracks if it leads to a dead end.
  • Efficiency: Backtracking is not the most efficient algorithm for solving Sudoku, but it is simple to implement and works well for small grids like 9x9.
  • Constraints Handling: The is_valid function ensures that all Sudoku constraints are respected.

Best Practices

  1. Input Validation: Always validate the input grid to ensure it adheres to Sudoku rules before attempting to solve it.
  2. Optimization: For larger grids or more complex puzzles, consider optimizing the backtracking algorithm using techniques like constraint propagation or heuristic methods.
  3. Error Handling: Implement error handling to manage unexpected inputs or states.

Conclusion

The Sudoku solver implemented using backtracking is a classic example of how recursive algorithms can be used to solve constraint satisfaction problems. While it may not be the most efficient solution for very large puzzles, it provides a clear and understandable approach to solving Sudoku puzzles programmatically. By understanding the constraints and applying backtracking effectively, you can tackle similar problems in data structures and algorithms.


PreviousN-Queens ProblemNext Maze Solving using Backtracking

Recommended Gear

N-Queens ProblemMaze Solving using Backtracking