0%

Leetcode 54 螺旋矩阵

给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

还是直接模拟,写就完事了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
m, n = len(matrix), len(matrix[0])
first, second, third, forth = 0, n-1, m-1, 0
flag_matrix = [[False for i in range(n)] for j in range(m)]

area, count, switch = m*n, 0, 0
ans = []

while count != area:
if switch == 0:
for j in range(n):
if flag_matrix[first][j] == False:
ans.append(matrix[first][j])
flag_matrix[first][j] = True
count += 1
else:
continue

first += 1
switch = (switch+1)%4
continue

if switch == 1:
for i in range(m):
if flag_matrix[i][second] == False:
ans.append(matrix[i][second])
flag_matrix[i][second] = True
count += 1
else:
continue

second -= 1
switch = (switch+1)%4
continue

if switch == 2:
for j in range(n-1, -1, -1):
if flag_matrix[third][j] == False:
ans.append(matrix[third][j])
flag_matrix[third][j] = True
count += 1
else:
continue

third -= 1
switch = (switch+1)%4
continue

if switch == 3:
for i in range(m-1, -1, -1):
if flag_matrix[i][forth] == False:
ans.append(matrix[i][forth])
flag_matrix[i][forth] = True
count += 1
else:
continue

forth += 1
switch = (switch+1)%4
continue

return ans