diff --git a/task2.py b/task2.py index e69de29..db482a1 100644 --- a/task2.py +++ b/task2.py @@ -0,0 +1,88 @@ +import random as r +from collections import deque + +def generate_random_matrix(N, M): + """ + Генерирует матрицу N x M со случайными значениями 0, 1, 2 + """ + matrix = [[0] * M for _ in range(N)] + + for i in range(N): + for j in range(M): + matrix[i][j] = r.randint(0, 2) + + return matrix + +def count_good_apples(matrix): + count = 0 + for row in matrix: + count += row.count(1) + return count + +def solve_minutes(matrix): + if not matrix or not matrix[0]: + return -1 + + N = len(matrix) + M = len(matrix[0]) + queue = deque() + good_count = 0 + + matrix_copy = [row[:] for row in matrix] + + for i in range(N): + for j in range(M): + if matrix_copy[i][j] == 2: + queue.append((i, j, 0)) + elif matrix_copy[i][j] == 1: + good_count += 1 + + + if good_count == 0: + return 0 + + directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] + + minutes = 0 + + while queue: + i, j, time = queue.popleft() + minutes = max(minutes, time) + + for di, dj in directions: + ni, nj = i + di, j + dj + if 0 <= ni < N and 0 <= nj < M and matrix_copy[ni][nj] == 1: + matrix_copy[ni][nj] = 2 + good_count -= 1 + queue.append((ni, nj, time + 1)) + + return minutes if good_count == 0 else -1 + +def print_matrix(matrix): + + for row in matrix: + print("\t".join(map(str, row))) + +def main(): + print("Миграция червяков по яблокам") + + N = int(input("\nВведите количество строк N: ")) + M = int(input("Введите количество столбцов M: ")) + + matrix = generate_random_matrix(N, M) + + print("\nСгенерированная матрица:") + print_matrix(matrix) + + good_before = count_good_apples(matrix) + print(f"Количество хороших яблок изначально: {good_before}") + + result = solve_minutes(matrix) + + if result == -1: + print("\nРезультат: -1 (червяки не научились летать)") + else: + print(f"\nРезультат: {result} минут") + +if __name__ == "__main__": + main() \ No newline at end of file