Skip to content

Commit 590e0fe

Browse files
authored
Create Spiral Matrix - Leetcode 54.py
1 parent 4fd514c commit 590e0fe

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Spiral Matrix - Leetcode 54.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
class Solution:
2+
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
3+
m, n = len(matrix), len(matrix[0])
4+
ans = []
5+
i, j = 0, 0
6+
UP, RIGHT, DOWN, LEFT = 0, 1, 2, 3
7+
direction = RIGHT
8+
9+
UP_WALL = 0
10+
RIGHT_WALL = n
11+
DOWN_WALL = m
12+
LEFT_WALL = -1
13+
14+
while len(ans) != m*n:
15+
if direction == RIGHT:
16+
while j < RIGHT_WALL:
17+
ans.append(matrix[i][j])
18+
j += 1
19+
i, j = i+1, j-1
20+
RIGHT_WALL -= 1
21+
direction = DOWN
22+
elif direction == DOWN:
23+
while i < DOWN_WALL:
24+
ans.append(matrix[i][j])
25+
i += 1
26+
i, j = i-1, j-1
27+
DOWN_WALL -= 1
28+
direction = LEFT
29+
elif direction == LEFT:
30+
while j > LEFT_WALL:
31+
ans.append(matrix[i][j])
32+
j -= 1
33+
i, j = i-1, j+1
34+
LEFT_WALL += 1
35+
direction = UP
36+
else:
37+
while i > UP_WALL:
38+
ans.append(matrix[i][j])
39+
i -= 1
40+
i, j = i+1, j+1
41+
UP_WALL += 1
42+
direction = RIGHT
43+
44+
return ans
45+
# Time: O(m*n)
46+
# Space: O(1)

0 commit comments

Comments
 (0)