【LeetCode每天一题】Spiral Matrix II(螺旋数组II)
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)。
解决代码
1 def generateMatrix(self, n):
2 """
3 :type n: int
4 :rtype: List[List[int]]
5 """
6 if n == 0 or n == 1:
7 return 0 if n == 0 else [[1]]
10 nums = 1
11 up, down, left, right = 0, n-1, 0, n-1 # 上下左右变量
12 res = []
13 for i in range(n): # 结果矩阵
14 res.append([0]*n)
15
16 while left < right: # 循环条件,也可以是 up< down。 因为是n*n矩阵,所以可以这样。
17 for i in range(left, right):
18 res[up][i] = nums
19 nums+= 1
20
21 for i in range(up, down):
22 res[i][right] = nums
23 nums += 1
24
25 for i in range(right, left, -1):
26 res[down][i] = nums
27 nums += 1
28
29 for i in range(down, up, -1):
30 res[i][left] = nums
31 nums += 1
32 up, down, left, right = up+1, down-1, left+1, right-1
33
34 if n % 2: # 如果是奇数的话,中心还有一个元素。
35 res[left][right] = nums
36 return res