Freedom Sale
Independence Day Special — Unlock the AI Path 70% off our most popular AI course · Limited time offer
--Days
--Hrs
--Min
--Sec
Claim Your Discount
✦ Intermediate ⏱ 30 min

🔢 Build a Sudoku Solver with Python

🎯 What You'll Build

A Python program that solves any valid Sudoku puzzle in milliseconds using backtracking — an elegant recursive algorithm with no libraries required.

📋 What You'll Need

1

Represent the board and display it

A Sudoku board is a 9×9 grid. Use 0 for empty cells.

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],
]

def print_board(b):
    for i, row in enumerate(b):
        if i % 3 == 0 and i != 0:
            print("------+-------+------")
        line = ""
        for j, val in enumerate(row):
            if j % 3 == 0 and j != 0:
                line += " | "
            line += str(val) if val else "."
            if j < 8: line += " "
        print(line)

print_board(board)
5 3 . | . 7 . | . . .
6 . . | 1 9 5 | . . .
. 9 8 | . . . | . 6 .
------+-------+------
8 . . | . 6 . | . . 3
4 . . | 8 . 3 | . . 1
7 . . | . 2 . | . . 6
------+-------+------
. 6 . | . . . | 2 8 .
. . . | 4 1 9 | . . 5
. . . | . 8 . | . 7 9
2

Write the constraint checker

Before placing a number, check it does not already appear in the row, column, or 3×3 box.

def is_valid(board, row, col, num):
    # Check row
    if num in board[row]:
        return False

    # Check column
    if num in [board[r][col] for r in range(9)]:
        return False

    # Check 3x3 box
    box_row = (row // 3) * 3
    box_col = (col // 3) * 3
    for r in range(box_row, box_row + 3):
        for c in range(box_col, box_col + 3):
            if board[r][c] == num:
                return False

    return True
3

Implement backtracking to solve the puzzle

Try each number 1–9 in each empty cell. If a number leads to a contradiction, backtrack and try the next one.

import time

def solve(board):
    for row in range(9):
        for col in range(9):
            if board[row][col] == 0:          # found an empty cell
                for num in range(1, 10):       # try 1–9
                    if is_valid(board, row, col, num):
                        board[row][col] = num  # place the number
                        if solve(board):       # recurse
                            return True
                        board[row][col] = 0    # backtrack
                return False                   # no valid number found
    return True  # board is complete

start = time.time()
if solve(board):
    print_board(board)
    print(f"\nSolved in {(time.time()-start)*1000:.2f}ms")
else:
    print("No solution exists.")
5 3 4 | 6 7 8 | 9 1 2
6 7 2 | 1 9 5 | 3 4 8
1 9 8 | 3 4 2 | 5 6 7
------+-------+------
8 5 9 | 7 6 1 | 4 2 3
4 2 6 | 8 5 3 | 7 9 1
7 1 3 | 9 2 4 | 8 5 6
------+-------+------
9 6 1 | 5 3 7 | 2 8 4
2 8 7 | 4 1 9 | 6 3 5
3 4 5 | 2 8 6 | 1 7 9

Solved in 3.14ms
💡 Tip: Backtracking is the core algorithm behind constraint satisfaction problems, chess engines, and pathfinding. The same pattern — try → recurse → undo — solves N-Queens, maze generation, and crossword puzzles.

🎉 You Did It!

Your solver handles the hardest Sudoku puzzles in under 50ms. Backtracking is a fundamental CS interview algorithm — understanding it deeply is worth more than memorising it.

Found something wrong?

Spotted a bug, broken code, or something that doesn't look right? Tell us what's off and we'll fix it.