Skip to content

Commit 1b67a00

Browse files
Added spiral-order
1 parent 2bdc802 commit 1b67a00

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

spiral_order_traversal.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution:
2+
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
3+
if not matrix:
4+
return []
5+
sz, sz0 = len(matrix) - 1, len(matrix[0]) - 1
6+
rowBegin, rowEnd, colBegin, colEnd = 0, sz, 0, sz0
7+
ans = []
8+
while rowBegin <= rowEnd and colBegin <= colEnd:
9+
#left to right
10+
for i in range(colBegin, colEnd + 1):
11+
ans.append(matrix[rowBegin][i])
12+
rowBegin += 1
13+
14+
#top to bottom
15+
for i in range(rowBegin, rowEnd + 1):
16+
ans.append(matrix[i][colEnd])
17+
colEnd -= 1
18+
19+
#right to left
20+
if rowBegin <= rowEnd:
21+
for i in range(colEnd, colBegin - 1, -1):
22+
ans.append(matrix[rowEnd][i])
23+
rowEnd -= 1
24+
25+
#bottom to top
26+
if colBegin <= colEnd:
27+
for i in range(rowEnd, rowBegin - 1, -1):
28+
ans.append(matrix[i][colBegin])
29+
colBegin += 1
30+
return ans
31+
32+

0 commit comments

Comments
 (0)