输入一个正整数,生成一个n*n的二维数组矩阵,最外圈数字为1,内圈呈递增趋势,圈逐渐缩小,数字逐渐增大
时间: 2024-10-05 13:05:03 浏览: 50
要创建一个满足描述的二维数组矩阵,你可以使用嵌套循环来填充每个元素。这是一个简单的 Python 代码示例:
```python
def generate_matrix(n):
# 创建一个 n x n 的空矩阵
matrix = [[0] * n for _ in range(n)]
# 从中心开始向外填充数字
current_value = 1
row, col = n // 2, n // 2
while row >= 0 and col >= 0 and row < n and col < n:
matrix[row][col] = current_value
current_value += 1
row -= 1
col += 1 # 右上到左下
if row >= 0 and col < n:
matrix[row][col] = current_value
current_value += 1
elif row < n and col >= 0:
matrix[row][col] = current_value
current_value += 1
elif row < n and col < n:
matrix[row][col] = current_value
current_value += 1
else: # 如果到达边界,反转方向
row += 1
col -= 1 # 左下到右上
return matrix
# 测试生成5x5的矩阵
n = 5
matrix = generate_matrix(n)
for row in matrix:
print(row)
阅读全文
相关推荐
















