59. 螺旋矩阵 II
Difficulty: 中等
给你一个正整数 n
,生成一个包含 1
到 n<sup>2</sup>
所有元素,且元素按顺时针顺序螺旋排列的 n x n
正方形矩阵 matrix
。
示例 1:
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1
输出:[[1]]
提示:
1 <= n <= 20
Solution
跟54题属于同一道题,只不过此题不需要考虑特殊的矩阵形态。
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
res = [[0] * n for _ in range(n)]
left, top, right, down = 0, 0, n - 1, n - 1
cnt = 1
while left <= right and top <= down:
for i in range(left, right + 1):
res[top][i] = cnt
cnt += 1
for i in range(top + 1, down + 1):
res[i][right] = cnt
cnt += 1
for i in range(right - 1, left, -1):
res[down][i] = cnt
cnt += 1
for i in range(down, top, -1):
res[i][left] = cnt
cnt +=1
left += 1
top += 1
right -= 1
down -= 1
return res