Python
Python

 

 

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

  1. Ensure Python is installed on your system.
  2. Copy the code into a file named sudoku_solver.py.
  3. Open a terminal or command prompt and navigate to the directory containing the file.
  4. Run the script using the command: python sudoku_solver.py.
  5. View the original and solved Sudoku puzzles in the terminal output.
© 2024 Learn Programming. All Rights Reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)