Uriel's Corner

Research Associate @ Harvard University / Research Interests: Computer Vision, Biomedical Image Analysis, Machine Learning
posts - 0, comments - 50, trackbacks - 0, articles - 594
类似54,反向操作,将1~n^2按螺旋次序填入n*n的二维数组,思路也和54一样


 1 #59
 2 #Runtime: 11 ms (Beats 96.98%)
 3 #Memory: 13.2 MB (Beats 99.66%)
 4 
 5 class Solution(object):
 6     def generateMatrix(self, n):
 7         """
 8         :type n: int
 9         :rtype: List[List[int]]
10         """
11         fg = [[0] * n for _ in range(n)]
12         fg[0][0] = 1
13         i, j, cnt, t = 0, 0, 1, 0
14         while cnt < n**2:
15             if t % 4 == 0:
16                 while j < n - 1 and not fg[i][j + 1]:
17                     j += 1
18                     cnt += 1
19                     fg[i][j] = cnt
20             elif t % 4 == 1:
21                 while i < n - 1 and not fg[i + 1][j]:
22                     i += 1
23                     cnt += 1
24                     fg[i][j] = cnt
25             elif t % 4 == 2:
26                 while j >= 0 and not fg[i][j - 1]:
27                     j -= 1
28                     cnt += 1
29                     fg[i][j] = cnt
30             elif t % 4 == 3:
31                 while i >= 0 and not fg[i - 1][j]:
32                     i -= 1
33                     cnt += 1
34                     fg[i][j] = cnt
35             t += 1
36         return fg

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理