题目
给你一个正整数
n
,生成一个包含1
到n2
所有元素,且元素按顺时针顺序螺旋排列的n x n
正方形矩阵matrix
。
解题
def generateMatrix(n):
matrix = [[0] * n for _ in range(n)]
top, bottom = 0, n - 1
left, right = 0, n - 1
num = 1
while top <= bottom and left <= right:
# 从左到右填充
for i in range(left, right + 1):
matrix[top][i] = num
num += 1
top += 1
# 从上到下填充
for i in range(top, bottom + 1):
matrix[i][right] = num
num += 1
right -= 1
if top <= bottom:
# 从右到左填充
for i in range(right, left - 1, -1):
matrix[bottom][i] = num
num += 1
bottom -= 1
if left <= right:
# 从下到上填充
for i in range(bottom, top - 1, -1):
matrix[i][left] = num
num += 1
left += 1
return matrix
# 测试
n = 3
result = generateMatrix(n)
for row in result:
print(row)