给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
最近实验室SB项目比较忙,算了一下快一周多没写程序,明天调试完毕就应该可以恢复原来的状态。最近的程序由于博主的ubuntu开发环境由原来的python 2.7换成了python 3,如果出错可以更换一下,博主也建议开始使用python 3
方法一:首先应该分析这样的螺旋矩阵的特点,可以尝试先实现一个3×3的矩阵,然后渐渐就能发现规律了,博主先添加了一个mark矩阵标记已经填过数值的位置,方便循环的中止,但这样会增加空间复杂度,效率在Leetcode中还可以。
class Solution:
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
if n == 0:
return []
if n == 1:
return [[1]]
result = [[0 for i in range(n)] for i in range(n)]
mark = [[0 for i in range(n)] for i in range(n)]
i = j = 0
num = 1
while i < n and j < n:
while i < n and mark[i][j] != 1:
result[j][i] = num
mark[i][j] = 1
num += 1
i += 1
j += 1
i -= 1
while j < n and mark[i][j] != 1:
result[j][i] = num
mark[i][j] = 1
num += 1
j += 1
j -= 1
i -= 1
while i > -1 and mark[i][j] != 1:
result[j][i] = num
mark[i][j] = 1
num += 1
i -= 1
i += 1
j -= 1
while j > 0 and mark[i][j] != 1:
result[j][i] = num
mark[i][j] = 1
num += 1
j -= 1
j += 1
i += 1
while i < n-1 and mark[i][j] != 1:
result[j][i] = num
mark[i][j] = 1
i += 1
num += 1
j += 1
i -= 1
return result