题目链接

题目描述

给你一个正整数 n ,生成一个包含 1n 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix

示例

示例1:

输入:n = 3 输出:[[1,2,3],[8,9,4],[7,6,5]]

提示

  • 1 <= n <= 20

    思路

    模拟

    本题与0054-螺旋矩阵类似,直接模拟即可。

    题解

    1. class Solution:
    2. def generateMatrix(self, n: int) -> List[List[int]]:
    3. ret = [[0 for i in range(n)] for i in range(n)]
    4. if n == 0:
    5. return ret
    6. left, right = 0, n - 1
    7. top, bottom = 0, n - 1
    8. index = 1
    9. while index <= n * n:
    10. for i in range(left, right + 1):
    11. ret[top][i] = index
    12. index += 1
    13. top += 1
    14. for i in range(top, bottom + 1):
    15. ret[i][right] = index
    16. index += 1
    17. right -= 1
    18. for i in range(right, left - 1, -1):
    19. ret[bottom][i] = index
    20. index += 1
    21. bottom -= 1
    22. for i in range(bottom, top - 1, -1):
    23. ret[i][left] = index
    24. index += 1
    25. left += 1
    26. return ret

    复杂度分析

  • 时间复杂度:0059-螺旋矩阵II - 图1

  • 空间复杂度:0059-螺旋矩阵II - 图2