Solving Sudoku Puzzles Using Python: A Comprehensive Guide

Dasari Anji
3 min readDec 11, 2023

--

“Discover how leveraging powerful Python decorators can significantly streamline Sudoku-solving algorithms, cutting down complex code and enhancing readability. Dive into these decorators’ functionality, witnessing their efficiency and understanding their potential application in optimizing your Sudoku-solving Python scripts.”

SUDOKU PROBLEM (Image taken from Google Images)
SUDOKU PROBLEM IMAGE

Introduction:

Sudoku is a popular number puzzle game that involves filling a 9x9 grid with digits so that each column, each row, and each of the nine 3x3 subgrids contains all the digits from 1 to 9 without repetition. Solving Sudoku problems programmatically can be achieved using various algorithms and techniques. In this article, we’ll explore how to write Python code to solve Sudoku puzzles efficiently.

Explanation:

To solve Sudoku puzzles using Python, we’ll employ a backtracking algorithm, which systematically explores all possible solutions. The key idea behind backtracking is to make a series of choices and backtrack when a choice leads to a dead-end, eventually finding the correct solution.

The code for solving Sudoku puzzles involves creating a function that utilizes recursion and backtracking to fill in the grid. The algorithm works by iterating through empty cells, trying possible values, and checking if the current assignment is valid. If the assignment is valid, the algorithm moves on to the next cell; otherwise, it backtracks and tries a different value for the previous cell.

Here’s a Python code snippet demonstrating the Sudoku-solving algorithm:

def solve_sudoku(board):
def is_valid(row, col, num):
for i in range(9):
if board[row][i] == num or board[i][col] == num or board[(row//3)*3 + i//3][(col//3)*3 + i%3] == num:
return False
return True

def solve():
for i in range(9):
for j in range(9):
if board[i][j] == '.':
for num in map(str, range(1, 10)):
if is_valid(i, j, num):
board[i][j] = num
if solve():
return True
board[i][j] = '.'
return False
return True

solve()

# Usage of the code
# Creating a 9x9 Sudoku board as a list of lists
# Here we need to put the question sudoku along with the given starting number
# and in place of empty place which we need to solve we kept as '.' or '0'
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"]
]

solve_sudoku(board)
# Displaying the solved Sudoku board
for row in board:
print(' '.join(row))

The function: solve_sudoku(board): This function takes a 9x9 Sudoku board represented as a list of lists (board) as input and solves the Sudoku puzzle.

Function: is_valid(row, col, num) This helper function checks whether placing a number numat a given cell (row, col) in the Sudoku grid is valid according to Sudoku rules. It checks the current row, column, and 3x3 subgrid to ensure that num does not violate any Sudoku rules.

Function: solve() This is the core recursive function that uses backtracking to solve the Sudoku puzzle. It iterates through each cell in the board and tries to fill it with numbers from 1 to 9, provided the cell is empty (represented by ‘ . ’).

If it finds an empty cell, it tries each number and checks if it's valid using the is_valid() function. If the number is valid, it fills the cell with that number and recursively calls solve() to proceed with the next empty cell. If a number leads to a dead-end (no valid solution), it backtracks by resetting the cell to ‘ . ’ an tries the next number.

Usage: The provided board represents an unsolved 9x9 Sudoku puzzle. After calling solve_sudoku(board), the Sudoku-solving algorithm modifies the board in place, filling in the correct numbers. Finally, the code prints the solved Sudoku board by displaying each row.

OUTPUT:

SLOVED SUDOKU IMAGE

Conclusion:

In this article, we’ve covered a Python implementation of a backtracking algorithm to solve Sudoku puzzles. Understanding and implementing this algorithm can help you solve Sudoku problems and gain insights into backtracking techniques for solving other types of puzzles or problems. With this code, you can solve various Sudoku puzzles and expand your programming skills in Python.

--

--