给你一个正整数 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
2,程序代码
# -*- coding: utf-8 -*-"""
Created on Sat Jan 15 19:48:02 2022
Function: 螺旋矩阵 II
@author: 小梁aixj
"""classSolution(object):defgenerateMatrix(self, n):"""
:type n: int
:rtype: List[List[int]]
"""
res =[[0]* n for _ inrange(n)]
pos =[0,0]
move =(0,1)for index inrange(1, n * n +1):
res[pos[0]][pos[1]]= index
if res[(pos[0]+ move[0])% n][(pos[1]+ move[1])% n]>0:
move =(move[1],-1* move[0])
pos[0]= pos[0]+ move[0]
pos[1]= pos[1]+ move[1]return res
if __name__ =='__main__':
s = Solution()print(s.generateMatrix(3))