给你一个正整数 n
,生成一个包含 1
到 n2
所有元素,且元素按顺时针顺序螺旋排列的 n x n
正方形矩阵 matrix
。
示例 1:
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1
输出:[[1]]
提示:
1 <= n <= 20
# @lc app=leetcode.cn id=59 lang=python3
#
# [59] 螺旋矩阵 II
#
# @lc code=start
from calendar import c
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
rev=[[0]*n for i in range(n)]
rstart=0
cstart=0
rend=n-1
cend=n-1
mid=1
while cend>=cstart and rstart<=rend:
for l in range(cstart,cend+1):
rev[rstart][l]=mid
mid=mid+1
#rev.extend(matrix[rstart][cstart:cend+1])
for l in range(rstart+1,rend):
rev[l][cend]=mid
mid=mid+1
for l in range(cend,cstart-1,-1):
rev[rend][l]=mid
mid=mid+1
#rev.extend(matrix[rend][cstart:cend+1][::-1])
for l in range(rend-1,rstart,-1):
rev[l][cstart]=mid
mid=mid+1
cend=cend-1
cstart=cstart+1
rstart=rstart+1
rend=rend-1
if n//2!=n/2:
rev[n//2][n//2]=n*n
return rev