Skip to content

Commit fb062b0

Browse files
committed
54
1 parent 4895e9f commit fb062b0

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

spiral-matrix/jeldo.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution:
2+
def spiralOrder(self, m: list[list[int]]) -> list[int]:
3+
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
4+
result = []
5+
visited = set()
6+
heading, count = 0, 0
7+
r, c = 0, 0
8+
while count < len(m) * len(m[0]):
9+
result.append(m[r][c])
10+
visited.add((r, c))
11+
count += 1
12+
next_r, next_c = r + dirs[heading][0], c + dirs[heading][1]
13+
if not (0 <= next_r < len(m) and 0 <= next_c < len(m[0])) or (next_r, next_c) in visited:
14+
heading = (heading + 1) % 4
15+
next_r, next_c = r + dirs[heading][0], c + dirs[heading][1]
16+
r, c = next_r, next_c
17+
return result
18+
19+
20+
cases = [
21+
[[1, 2, 3], [4, 5, 6], [7, 8, 9]],
22+
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]],
23+
]
24+
25+
for c in cases:
26+
print(Solution().spiralOrder(c))

0 commit comments

Comments
 (0)