| Run ID | 作者 | 问题 | 语言 | 测评结果 | Time | Memory | 代码长度 | 提交时间 |
|---|---|---|---|---|---|---|---|---|
| 71361 | 彭士宝 | 数字方阵 | Python3 | Wrong Answer | 34 MS | 3840 KB | 1659 | 2024-04-22 22:11:26 |
def generate_spiral(n): # 初始化矩阵,填充1 matrix = [[1] * n for _ in range(n)] # 定义方向向量,依次为右、下、左、上 directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] # 当前方向索引 dir_idx = 0 # 当前位置 x, y = 0, 1 # 当前要填充的数字 num = 2 # 行和列的边界 row_bound, col_bound = n - 1, n - 1 # 填充数字 while num <= n * n: # 移动到下一个位置 for _ in range(2): # 每个方向填充两次数字 # 填充数字 matrix[y][x] = num num += 1 # 计算下一个位置 dx, dy = directions[dir_idx] nx, ny = x + dx, y + dy # 如果下一个位置在矩阵内且未被填充,则移动 if 0 <= nx < n and 0 <= ny < n and matrix[ny][nx] == 1: x, y = nx, ny else: # 否则,改变方向 dir_idx = (dir_idx + 1) % 4 x, y = x + directions[dir_idx][0], y + directions[dir_idx][1] # 更新行和列的边界 if dir_idx in [0, 2]: # 向右或向左移动 col_bound -= 1 x = max(x, col_bound + 1) else: # 向下或向上移动 row_bound -= 1 y = min(y, row_bound) # 返回矩阵 return matrix # 打印矩阵 def print_matrix(matrix): for row in matrix: print(' '.join(map(str, row))) # 输入正整数n n = int(input().strip()) # 生成并打印回型方阵 spiral_matrix = generate_spiral(n) print_matrix(spiral_matrix)
------Input------
5
------Answer-----
1 1 1 1 1 1 2 2 2 1 1 2 3 2 1 1 2 2 2 1 1 1 1 1 1
------Your output-----