Introduction
Sudoku is a popular logic-based number placement puzzle. The objective of this program is to solve a given Sudoku puzzle by filling the empty cells with digits such that every row, column, and 3×3 grid contains all digits from 1 to 9 exactly once. This program implements a backtracking algorithm to solve Sudoku puzzles efficiently.
Objective
The goal of this program is to automate the solving of Sudoku puzzles using Python, providing an accurate and efficient solution for even the most challenging puzzles.
Python Code
def print_board(board): for row in board: print(" ".join(str(cell) if cell != 0 else '.' for cell in row)) def is_valid(board, row, col, num): # Check row if num in board[row]: return False # Check column if num in [board[i][col] for i in range(9)]: return False # Check 3x3 grid start_row, start_col = 3 * (row // 3), 3 * (col // 3) for i in range(start_row, start_row + 3): for j in range(start_col, start_col + 3): if board[i][j] == num: return False return True def solve_sudoku(board): for row in range(9): for col in range(9): if board[row][col] == 0: 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 return False return True def main(): # Example Sudoku puzzle (0 represents empty cells) 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] ] print("Original Sudoku Puzzle:") print_board(sudoku_board) if solve_sudoku(sudoku_board): print("\nSolved Sudoku Puzzle:") print_board(sudoku_board) else: print("\nNo solution exists for the given Sudoku puzzle.") if __name__ == "__main__": main()
Program Explanation
This Python program solves Sudoku puzzles using the backtracking algorithm. Here’s a breakdown of the program structure:
print_board
: Displays the Sudoku board in a human-readable format.is_valid
: Checks whether placing a number in a specific cell is valid according to Sudoku rules.solve_sudoku
: Implements the backtracking algorithm to fill empty cells recursively until the puzzle is solved.main
: Initializes a Sudoku puzzle, prints the original puzzle, solves it, and prints the solved puzzle.
Steps to Run the Program
- Ensure Python is installed on your system.
- Copy the code into a file named
sudoku_solver.py
. - Open a terminal or command prompt and navigate to the directory containing the file.
- Run the script using the command:
python sudoku_solver.py
. - View the original and solved Sudoku puzzles in the terminal output.