题目:59. 螺旋矩阵 II
链接:https://leetcode-cn.com/problems/spiral-matrix-ii
给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。 示例: 输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
解题:
1、按照要求依次添加数字。
代码:
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
num = n * n
cur = 1
matrix = [[0] * n for i in range(n)]
left, right = 0, n - 1
top, bottom = 0, n - 1
while top <= bottom and left <= right:
for j in range(left, right + 1):
matrix[top][j] = cur
cur += 1
top += 1
for i in range(top, bottom + 1):
matrix[i][right] = cur
cur += 1
right -= 1
for j in range(right, left - 1, -1):
matrix[bottom][j] = cur
cur += 1
bottom -= 1
for i in range(bottom, top - 1, -1):
matrix[i][left] = cur
cur += 1
left += 1
return matrix