- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathSpiralMatrix.py
37 lines (37 loc) · 1.03 KB
/
SpiralMatrix.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
"""
https://leetcode.com/problems/spiral-matrix/
Given an m x n matrix, return all elements of the matrix in spiral order.
"""
classSolution(object):
defspiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
m=len(matrix)
n=len(matrix[0])
left=0
right=n-1
top=0
down=m-1
dir=0
x=[]
whiletop<=downandleft<=right:
ifdir==0:
foriinrange(left,right+1):
x.append(matrix[top][i])
top+=1
ifdir==1:
foriinrange(top,down+1):
x.append(matrix[i][right])
right-=1
ifdir==2:
foriinrange(right,left-1,-1):
x.append(matrix[down][i])
down-=1
ifdir==3:
foriinrange(down,top-1,-1):
x.append(matrix[i][left])
left+=1
dir=(dir+1)%4
returnx