Posted on 2023-05-09 14:48
Uriel 阅读(36)
评论(0) 编辑 收藏 引用 所属分类:
模拟 、
闲来无事重切Leet Code 、
大水题
将一个二维数组螺旋向内的顺序输出,简单模拟
Input: matrix =[
[1,2,3],
[4,5,6],
[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
1 #54
2 #Runtime: 18 ms (Beats 50.87%)
3 #Memory: 13.3 MB (Beats 90.64%)
4
5 class Solution(object):
6 def spiralOrder(self, matrix):
7 """
8 :type matrix: List[List[int]]
9 :rtype: List[int]
10 """
11 fg = [[0] * len(matrix[0]) for _ in range(len(matrix))]
12 ans = [matrix[0][0]]
13 fg[0][0] = 1
14 i, j, cnt, t = 0, 0, 1, 0
15 while cnt < len(matrix) * len(matrix[0]):
16 if t % 4 == 0:
17 while j < len(matrix[0]) - 1 and not fg[i][j + 1]:
18 j += 1
19 ans.append(matrix[i][j])
20 fg[i][j] = 1
21 cnt += 1
22 elif t % 4 == 1:
23 while i < len(matrix) - 1 and not fg[i + 1][j]:
24 i += 1
25 ans.append(matrix[i][j])
26 fg[i][j] = 1
27 cnt += 1
28 elif t % 4 == 2:
29 while j >= 0 and not fg[i][j - 1]:
30 j -= 1
31 ans.append(matrix[i][j])
32 fg[i][j] = 1
33 cnt += 1
34 elif t % 4 == 3:
35 while i >= 0 and not fg[i - 1][j]:
36 i -= 1
37 ans.append(matrix[i][j])
38 fg[i][j] = 1
39 cnt += 1
40 t += 1
41 return ans