Run ID:78463

提交时间:2024-06-22 09:44:34

def print_spiral_matrix(n): # 初始化矩阵 matrix = [[0] * n for _ in range(n)] # 定义四个方向:右、下、左、上 directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] # 初始化方向索引和步数 dir_index = 0 step = 1 # 初始化起始位置 x, y = 0, 0 for num in range(1, n**2 + 1): # 将当前数字放入矩阵中 matrix[x][y] = num # 计算下一个位置 next_x, next_y = x + directions[dir_index][0], y + directions[dir_index][1] # 检查下一个位置是否有效(即在矩阵内且当前位置未访问) if 0 <= next_x < n and 0 <= next_y < n and matrix[next_x][next_y] == 0: x, y = next_x, next_y else: # 否则,改变方向 dir_index = (dir_index + 1) % 4 x, y = x + directions[dir_index][0], y + directions[dir_index][1] # 打印矩阵 for row in matrix: print(" ".join(map(str, row))) # 读取输入 n = int(input()) # 打印回型方阵 print_spiral_matrix(n)