Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
思路
之前做过一个旋转数组的题,当时是旋转打印矩阵,这次只是构造一个旋转数组。方案还是一样的,条件变量也一样。时间复杂度为O(n*n), 空间复杂度为O(n)。
解决代码
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
if n == 0 or n == 1:
return 0 if n == 0 else [[1]]
nums = 1
up, down, left, right = 0, n-1, 0, n-1 # 上下左右变量
res = []
for i in range(n): # 结果矩阵
res.append([0]*n) while left < right: # 循环条件,也可以是 up< down。 因为是n*n矩阵,所以可以这样。
for i in range(left, right):
res[up][i] = nums
nums+= 1 for i in range(up, down):
res[i][right] = nums
nums += 1 for i in range(right, left, -1):
res[down][i] = nums
nums += 1 for i in range(down, up, -1):
res[i][left] = nums
nums += 1
up, down, left, right = up+1, down-1, left+1, right-1 if n % 2: # 如果是奇数的话,中心还有一个元素。
res[left][right] = nums
return res