# # # @param n int整型 # @return int整型二维数组 # class Solution: def generateMatrix(self , n ): if n<= 0: return[] res = [[0 for i in range(n)] for j in range(n)] var = 1 l,r,d ,u = 0, n-1, n-1 , 0 while(l < r) and (u < d): # 从左到右 for i in range(l, r): res[u][i] = var var += 1 # 从上到下 for i in range(u,d): res[i][r] = var var += 1 # 从左到右 for i in range(r, l ,-1): res[d][i] = var var += 1 # 从下向上 for i in range(d, u, -1): res[i][l] = var var += 1 l += 1 r -= 1 d -= 1 u += 1 if (l==r): res[l][l] = n**2 return res # write code here
题目描述
给定一个整数n,将数字1到n^2n2按螺旋的顺序填入n×n的矩阵
例如:
给出的n=3,
你应该返回如下矩阵:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
此题是不是非常的熟悉,此时是我们之前做过的螺旋矩阵,知不道这是反过来了 之前是给你矩阵让你螺旋式输出,现在是你你维度螺旋式生成矩阵