-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpiral Matrix.py
40 lines (30 loc) · 1.05 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
class Solution:
def spiralOrder(self, mat: List[List[int]]) -> List[int]:
ans = []
n = len(mat) # no. of rows
m = len(mat[0]) # no. of columns
# Initialize the pointers reqd for traversal.
top = 0
left = 0
bottom = n - 1
right = m - 1
while (top <= bottom and left <= right):
# For moving left to right
for i in range(left, right + 1):
ans.append(mat[top][i])
top += 1
# For moving top to bottom.
for i in range(top, bottom + 1):
ans.append(mat[i][right])
right -= 1
# For moving right to left.
if (top <= bottom):
for i in range(right, left - 1, -1):
ans.append(mat[bottom][i])
bottom -= 1
# For moving bottom to top.
if (left <= right):
for i in range(bottom, top - 1, -1):
ans.append(mat[i][left])
left += 1
return ans