题目链接
题目描述
给你一个正整数 n ,生成一个包含 1 到 n 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
示例
示例1:
输入:n = 3 输出:[[1,2,3],[8,9,4],[7,6,5]]
提示
-
思路
模拟
本题与0054-螺旋矩阵类似,直接模拟即可。
题解
class Solution:def generateMatrix(self, n: int) -> List[List[int]]:ret = [[0 for i in range(n)] for i in range(n)]if n == 0:return retleft, right = 0, n - 1top, bottom = 0, n - 1index = 1while index <= n * n:for i in range(left, right + 1):ret[top][i] = indexindex += 1top += 1for i in range(top, bottom + 1):ret[i][right] = indexindex += 1right -= 1for i in range(right, left - 1, -1):ret[bottom][i] = indexindex += 1bottom -= 1for i in range(bottom, top - 1, -1):ret[i][left] = indexindex += 1left += 1return ret
复杂度分析
时间复杂度:
- 空间复杂度:
