AIAppleseed
  • Home
  • About
  • Contact
  • Home
  • About
  • Contact
Search

Python code that would allow someone to solve any Sudoku problem

Prompt:
Please wrote python code that would allow someone to solve any Sudoku problem

ChatGPT's response:
Certainly! Here's a Python implementation of a Sudoku solver using a backtracking algorithm. This code can solve any valid Sudoku puzzle.
def is_valid(board, row, col, num):
    # Check if num is not in the current row
    for i in range(9):
        if board[row][i] == num:
            return False
    
    # Check if num is not in the current column
    for i in range(9):
        if board[i][col] == num:
            return False
    
    # Check if num is not in the current 3x3 subgrid
    start_row, start_col = 3 * (row // 3), 3 * (col // 3)
    for i in range(3):
        for j in range(3):
            if board[start_row + i][start_col + j] == num:
                return False
    
    return True

def solve_sudoku(board):
    empty_pos = find_empty(board)
    if not empty_pos:
        return True  # Sudoku is solved
    
    row, col = empty_pos
    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  # Reset the cell and backtrack
    
    return False

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

def print_board(board):
    for row in board:
        print(" ".join(str(num) if num != 0 else '.' for num in row))

# Example usage
if __name__ == "__main__":
    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 board:")
    print_board(sudoku_board)
    
    if solve_sudoku(sudoku_board):
        print("\nSolved Sudoku board:")
        print_board(sudoku_board)
    else:
        print("No solution exists")

Here's a breakdown of the functions:
  1. is_valid(board, row, col, num): Checks if a number can be placed in the specified cell without violating Sudoku rules.
  2. solve_sudoku(board): Uses backtracking to solve the Sudoku puzzle. It recursively tries to fill the board and backtracks if it encounters an invalid placement.
  3. find_empty(board): Finds an empty cell (represented by 0) in the board.
  4. print_board(board): Prints the Sudoku board in a readable format.
To use the solver, you need to fill the sudoku_board with the puzzle you want to solve, replacing the empty cells with 0. Then, run the script to see the solved board.

  • Home
  • About
  • Contact