问题描述:
给定一个正整数n
,生成一个包含 1
到
n
2
n^2
n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入:
3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
问题分析:
这个题目和《54. Spiral Matrix》解决方法一样,不同的在于一个是读出来一个是写进去,然后要同步一个计数器即可。
(1)因为从第一个
位置开始,顺时针螺旋填写
,可理解为,一层一层的填充
。
(2)所以,就可以一层一层向里处理,依次是,最上层
、最右层
、最下层
、最左层
,即这一圈处理完毕,循环进入下一个内圈,直到结束。其中需要注意的时间,最后剩下的可能为一行,或者一列,这时,要单独判断。其中,每次填写一次,就更新一下计数器
。
(3)需要注意的地方就是,各种边界问题,比较繁琐,要细心即可。
Python3实现:
# @Time :2018/11/21
# @Author :LiuYinxing
class Solution:
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
if n == 1: return [[1]]
matrix = [[0] * n for _ in range(n)]
top = 0 # 上边
bottom = n - 1 # 下边
left = 0 # 左边
right = n - 1 # 右边
cnt = 1
while top < bottom and left < right:
for y in range(left, right + 1): # 写入最上面一行数据
matrix[top][y] = cnt
cnt += 1
for x in range(top + 1, bottom): # 写入最右边一列数据
matrix[x][right] = cnt
cnt += 1
for y in range(right, left - 1, -1): # 写入最下面一行数据
matrix[bottom][y] = cnt
cnt += 1
for x in range(bottom - 1, top, -1): # 写入最左边一列数据
matrix[x][left] = cnt
cnt += 1
top, bottom, left, right = top + 1, bottom - 1, left + 1, right - 1 # 四个边界,分别向内部移动一个位置
if top == bottom: # 如果最后剩下一行数据
for y in range(left, right + 1):
matrix[top][y] = cnt
cnt += 1
elif left == right: # 如果最后剩下一列数据
for x in range(top, bottom + 1):
matrix[x][right] = cnt
cnt += 1
return matrix
if __name__ == '__main__':
matrix = Solution().generateMatrix(6)
for row in matrix:
print(row)
声明: 总结学习,有问题或不妥之处,可以批评指正哦。