Skip to content

Commit 3470fbd

Browse files
committed
- Spiral Matrix #282
1 parent 8d0daa1 commit 3470fbd

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

spiral-matrix/ayosecu.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
from typing import List
2+
3+
class Solution:
4+
"""
5+
- Time Complexity: O(N), N = len(matrix) * len(matrix[0])
6+
- Space Complexity: O(1), If output variable (result) excluded.
7+
"""
8+
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
9+
result = []
10+
11+
while matrix:
12+
result += matrix.pop(0) # append a top row
13+
if matrix and matrix[0]:
14+
for row in matrix:
15+
result.append(row.pop()) # append elements in right side (down direction)
16+
if matrix:
17+
result += matrix.pop()[::-1] # append a bottom row with reversed
18+
if matrix and matrix[0]:
19+
for row in matrix[::-1]:
20+
result.append(row.pop(0)) # append elements in left side (up direction)
21+
22+
return result
23+
24+
tc = [
25+
([[1,2,3],[4,5,6],[7,8,9]], [1,2,3,6,9,8,7,4,5]),
26+
([[1,2,3,4],[5,6,7,8],[9,10,11,12]], [1,2,3,4,8,12,11,10,9,5,6,7])
27+
]
28+
29+
sol = Solution()
30+
for i, (m, e) in enumerate(tc, 1):
31+
r = sol.spiralOrder(m)
32+
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")

0 commit comments

Comments
 (0)