- Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathspiral_matrix.py
52 lines (44 loc) · 1.58 KB
/
spiral_matrix.py
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
classSolution:
defspiralOrder(self, matrix: List[List[int]]) ->List[int]:
ifmatrix== []:
return []
test_matrix= [ [ 1, 2 ], [ 4, 5 ], [ 7, 8 ] ]
print( len(test_matrix) )
print( len(test_matrix[0]) )
top=0
bottom=len(matrix)-1
left=0
right=len(matrix[0])-1
new_list= []
# we define the directions
# 0: go right
# 1: go down
# 2: go left
# 3: go up
direction=0
whileTrue:
# 0: go right
ifdirection==0:
foriinrange(left, right+1):
new_list.append(matrix[top][i])
top+=1
# 1: go down
elifdirection==1:
foriinrange(top, bottom+1):
new_list.append(matrix[i][right])
right-=1
# 2: go left
# note: be careful about the 'range'
elifdirection==2:
foriinrange(right, left-1, -1):
new_list.append(matrix[bottom][i])
bottom-=1
# 3: go up
elifdirection==3:
foriinrange(bottom, top-1, -1):
new_list.append(matrix[i][left])
left+=1
# change the direction!!!
direction= (direction+1) %4
iftop>bottomorleft>right:
returnnew_list