59:螺旋矩阵II
程序员文章站
2022-05-20 13:46:43
...
问题描述
给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例
输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
问题分析
没啥好分析的,模拟一下旋转即可。
AC代码
class Solution:
def generateMatrix(self, n: int):
res = [[0 for i in range(n)] for i in range(n)]
left = top = 0
bottom = right = n
flag = 1
i = 1
while i <= n*n:
if flag == 1:
for j in range(left,right):
res[top][j] = i
i += 1
top += 1
flag = 2
elif flag == 2:
for j in range(top,bottom):
res[j][right-1] = i
i += 1
right -= 1
flag = 3
elif flag == 3:
for j in range(right-1,left-1,-1):
res[bottom-1][j] = i
i += 1
bottom -= 1
flag = 4
elif flag == 4:
for j in range(bottom-1,top-1,-1):
res[j][left] = i
i += 1
left += 1
flag = 1
return res
s = Solution()
s.generateMatrix(4)