1 class Solution:
 2     def generateMatrix(self, n: int) -> 'List[List[int]]':
 3         res = [[0 for _ in range(n)]for _ in range(n)]
 4         x,y = 0,0
 5         count = 1
 6         while x <= n and y <= n:
 7             for j in range(y,n):
 8                 res[x][j] = count
 9                 count += 1
10             for i in range(x + 1,n):
11                 res[i][n - 1] = count
12                 count += 1
13             for j in range(n - 2,y - 1,-1):
14                 res[n - 1][j] = count
15                 count += 1
16             for i in range(n - 2,x,-1):
17                 res[i][y] = count
18                 count += 1
19             
20             x += 1
21             y += 1
22             n -= 1
23         return res

本题思路同leetcode54一样,二维数组螺旋遍历。

起点坐标:沿主对角线,从左上向右下移动,即 x += 1, y += 1

终点坐标:每次缩小n的范围,即 n -= 1

能完整访问一个"外圈",就可以按照相同的方式,访问"内圈",一层一层的访问。

posted on 2019-12-10 09:40  Sempron2800+  阅读(198)  评论(0编辑  收藏  举报