Run ID:78405

提交时间:2024-06-19 22:08:51

def generate_spiral_matrix(n): matrix = [[0] * n for _ in range(n)] directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] dir_index = 0 row, col = n num = 1 for _ in range(n * n): matrix[row][col] = num num += next_row = row + directions[dir_index][0] next_col = col + directions[dir_index][1] if 0 <= next_row < n and 0 <= next_col < n and matrix[next_row][next_col] == 0: row, col = next_row, next_col else: dir_index = (dir_index + 1) % 4 row += directions[dir_index][0] col += directions[dir_index][1] return '\n'.join(' '.join(map(str, row)) for row in matrix) n = int(input().strip()) print(generate_spiral_matrix(n))