leetcode 54. 螺旋矩阵

解题思路

模拟

时间复杂度

O(mn)

空间复杂度

O(mn)

代码

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
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
ret = []
col = len(matrix[0])
row = len(matrix)
visited = [[False]*col for i in range(row)]
x = 0
y = 0
direct = 'right'

while True:
if x >= row or y >= col or visited[x][y]:
break

ret.append(matrix[x][y])
visited[x][y] = True

if direct == 'right':
if y == col - 1 or visited[x][y+1]:
direct = 'down'
x += 1
else:
y += 1
continue

if direct == 'down':
if x == row - 1 or visited[x+1][y]:
direct = 'left'
y -= 1
else:
x += 1
continue

if direct == 'left':
if y == 0 or visited[x][y-1]:
direct = 'up'
x -= 1
else:
y -= 1
continue

if direct == 'up':
if x == 0 or visited[x-1][y]:
direct = 'right'
y += 1
else:
x -= 1
continue

return ret