|
| 1 | +import random |
| 2 | + |
| 3 | +class Sudoku: |
| 4 | + def __init__(self, grid): |
| 5 | + self.grid = grid |
| 6 | + |
| 7 | + @staticmethod |
| 8 | + def generate_empty_grid(): |
| 9 | + return [[0 for _ in range(9)] for _ in range(9)] |
| 10 | + |
| 11 | + @staticmethod |
| 12 | + def is_valid_move(grid, row, col, num): |
| 13 | + # Check if the number is already present in the row, column, or 3x3 subgrid |
| 14 | + return (num not in grid[row] and |
| 15 | + num not in (grid[i][col] for i in range(9)) and |
| 16 | + num not in (grid[i][j] for i in range(row - row % 3, row - row % 3 + 3) |
| 17 | + for j in range(col - col % 3, col - col % 3 + 3))) |
| 18 | + |
| 19 | + @staticmethod |
| 20 | + def generate_sudoku(): |
| 21 | + grid = Sudoku.generate_empty_grid() |
| 22 | + Sudoku.solve_sudoku(grid) |
| 23 | + Sudoku.remove_cells(grid, random.randint(30, 45)) # Adjust the range for the number of empty cells |
| 24 | + return grid |
| 25 | + |
| 26 | + @staticmethod |
| 27 | + def solve_sudoku(grid): |
| 28 | + empty_cell = Sudoku.find_empty_cell(grid) |
| 29 | + if not empty_cell: |
| 30 | + return True |
| 31 | + row, col = empty_cell |
| 32 | + for num in random.sample(range(1, 10), 9): |
| 33 | + if Sudoku.is_valid_move(grid, row, col, num): |
| 34 | + grid[row][col] = num |
| 35 | + if Sudoku.solve_sudoku(grid): |
| 36 | + return True |
| 37 | + grid[row][col] = 0 |
| 38 | + return False |
| 39 | + |
| 40 | + @staticmethod |
| 41 | + def find_empty_cell(grid): |
| 42 | + for i in range(9): |
| 43 | + for j in range(9): |
| 44 | + if grid[i][j] == 0: |
| 45 | + return i, j |
| 46 | + return None |
| 47 | + |
| 48 | + @staticmethod |
| 49 | + def remove_cells(grid, num_cells_to_remove): |
| 50 | + for _ in range(num_cells_to_remove): |
| 51 | + row = random.randint(0, 8) |
| 52 | + col = random.randint(0, 8) |
| 53 | + if grid[row][col] != 0: |
| 54 | + grid[row][col] = 0 |
| 55 | + |
| 56 | + @staticmethod |
| 57 | + def print_grid(grid): |
| 58 | + for row in grid: |
| 59 | + print(" ".join(map(str, row))) |
| 60 | + |
| 61 | +def main(): |
| 62 | + print("Generating Sudoku puzzle...") |
| 63 | + sudoku_grid = Sudoku.generate_sudoku() |
| 64 | + print("Sudoku puzzle:") |
| 65 | + Sudoku.print_grid(sudoku_grid) |
| 66 | + |
| 67 | + user_input = input("\nWould you like to see the solution? (yes/no): ").strip().lower() |
| 68 | + if user_input in ['yes', 'y']: |
| 69 | + solved_grid = [row[:] for row in sudoku_grid] # Create a copy of the grid to solve |
| 70 | + if Sudoku.solve_sudoku(solved_grid): |
| 71 | + print("Sudoku solution:") |
| 72 | + Sudoku.print_grid(solved_grid) |
| 73 | + else: |
| 74 | + print("No solution found.") |
| 75 | + else: |
| 76 | + print("Solution not displayed.") |
| 77 | + |
| 78 | +if __name__ == "__main__": |
| 79 | + main() |
0 commit comments