Amazing-Python-Scripts

Форк
0
133 строки · 4.1 Кб
1
import math
2

3

4
def is_valid(board, row, col, num, group_size):
5
    # Check if 'num' can be placed in the given position without violating the rules
6
    # Check row and column
7
    for i in range(len(board)):
8
        if board[i][col] == num or board[row][i] == num:
9
            return False
10

11
    # Check the group constraints
12
    group_start_row, group_start_col = row - \
13
        row % group_size, col - col % group_size
14
    for i in range(group_size):
15
        for j in range(group_size):
16
            if board[group_start_row + i][group_start_col + j] == num:
17
                return False
18

19
    return True
20

21

22
def find_empty_cell(board):
23
    # Find an empty cell (cell with value 0) on the board and return its coordinates
24
    for i in range(len(board)):
25
        for j in range(len(board)):
26
            if board[i][j] == 0:
27
                return i, j
28
    return None
29

30

31
def solve_kenken(board, group_size):
32
    # Function to solve the KenKen puzzle using backtracking
33
    empty_cell = find_empty_cell(board)
34
    if not empty_cell:
35
        # If no empty cell found, the board is solved
36
        return True
37

38
    row, col = empty_cell
39

40
    for num in range(1, len(board) + 1):
41
        if is_valid(board, row, col, num, group_size):
42
            board[row][col] = num
43

44
            if solve_kenken(board, group_size):
45
                return True
46

47
            board[row][col] = 0
48

49
    return False
50

51

52
def validate_puzzle_input(size, groups):
53
    # Function to validate the user-provided KenKen puzzle input
54
    # Check for the following conditions:
55
    # 1. The board size is valid (greater than 1 and a perfect square)
56
    # 2. The number of groups is equal to the board size
57
    # 3. Each group has a valid target number (greater than 0)
58
    # 4. Each group operation is valid (+, -, *, /)
59

60
    if size <= 1 or int(size ** 0.5) ** 2 != size:
61
        print("Invalid board size. The size should be greater than 1 and a perfect square.")
62
        return False
63

64
    if len(groups) != size:
65
        print(f"Invalid number of groups. Expected {size} groups.")
66
        return False
67

68
    valid_operations = {'+', '-', '*', '/'}
69
    for target, operation in groups:
70
        if target <= 0:
71
            print(
72
                "Invalid target number. The target number should be greater than 0 for each group.")
73
            return False
74
        if operation not in valid_operations:
75
            print("Invalid operation. Valid operations are '+', '-', '*', or '/'.")
76
            return False
77

78
    return True
79

80

81
def get_puzzle_input():
82
    # Function to get the KenKen puzzle input from the user
83
    size = int(input("Enter the size of the grid (e.g., 5 for a 5x5 puzzle): "))
84
    group_size = int(
85
        input("Enter the size of each group (e.g., 3 for a standard 9x9 puzzle): "))
86

87
    groups = []
88
    for i in range(size):
89
        while True:
90
            try:
91
                group_target = int(
92
                    input(f"Enter the target number for group {i + 1}: "))
93
                group_operation = input(
94
                    f"Enter the operation for group {i + 1} (+, -, *, /): ")
95
                groups.append((group_target, group_operation))
96
                break
97
            except ValueError:
98
                print("Invalid input. Please enter a valid target number and operation.")
99

100
    if validate_puzzle_input(size, groups):
101
        return size, group_size, groups
102
    else:
103
        print("Invalid puzzle input. Please try again.")
104
        return None
105

106

107
def print_board(board):
108
    # Function to pretty print the KenKen board
109
    for row in board:
110
        print(" ".join(str(num) if num != 0 else "-" for num in row))
111
    print()
112

113

114
def main():
115
    # Main function to run the KenKen puzzle solver
116
    print("KenKen Puzzle Solver")
117

118
    puzzle_input = get_puzzle_input()
119
    if puzzle_input:
120
        size, group_size, groups = puzzle_input
121

122
        # Initialize the board with zeros
123
        kenken_board = [[0 for _ in range(size)] for _ in range(size)]
124

125
        if solve_kenken(kenken_board, group_size):
126
            print("Solved KenKen Puzzle:")
127
            print_board(kenken_board)
128
        else:
129
            print("No solution exists.")
130

131

132
if __name__ == "__main__":
133
    main()
134

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.