题解 | 回型矩阵
回型矩阵
https://www.nowcoder.com/practice/36d5dfddc22c4f5b88a5b2a9de7db343
n = int(input())
# 创建一个 n x n 的矩阵,初始化为 0
matrix = [[0] * n for _ in range(n)]
count = 1 # 当前填充的数字
top, bottom, left, right = 0, n-1, 0, n-1 # 初始边界
while count <= n * n:
# 从左到右填充上边界
for i in range(left, right + 1):
matrix[top][i] = count
count += 1
top += 1
# 从上到下填充右边界
for i in range(top, bottom + 1):
matrix[i][right] = count
count += 1
right -= 1
# 从右到左填充下边界
if top <= bottom:
for i in range(right, left - 1, -1):
matrix[bottom][i] = count
count += 1
bottom -= 1
# 从下到上填充左边界
if left <= right:
for i in range(bottom, top - 1, -1):
matrix[i][left] = count
count += 1
left += 1
# 打印矩阵,每个元素后跟一个空格,行末换行
for i in range(n):
# 格式化打印,确保数字对齐(可选,根据需要调整)
print(' '.join(str(matrix[i][j]) for j in range(n)))
查看20道真题和解析
