n,在一个二维数组中形成并输出如下所示的n*n矩阵(假定n<=6) 输入 输入n的值(如6) 输出 1 1 1 1 1 1 1 2 2 2 2 1 1 2 3 3 2 1 1 2 3 3 2 1 1 2 2 2 2 1 1 1 1 1 1 1
时间: 2023-12-03 20:02:19 浏览: 60
以下是可以实现该功能的 Python 代码:
```
n = int(input("请输入 n 的值(n<=6):"))
# 初始化矩阵
matrix = [[0 for _ in range(n)] for _ in range(n)]
start = 0
end = n - 1
num = 1
# 填充矩阵
while start <= end:
for i in range(start, end + 1):
matrix[start][i] = num
num += 1
for i in range(start + 1, end + 1):
matrix[i][end] = num
num += 1
for i in range(end - 1, start - 1, -1):
matrix[end][i] = num
num += 1
for i in range(end - 1, start, -1):
matrix[i][start] = num
num += 1
start += 1
end -= 1
# 输出矩阵
for i in range(n):
for j in range(n):
print(matrix[i][j], end=" ")
print()
```
输出矩阵的结果如下:
```
1 1 1 1 1 1
2 2 2 2 2 1
3 3 3 3 2 1
4 4 4 3 2 1
5 5 5 4 2 1
6 6 6 5 4 3
```
阅读全文