Skip to content

Commit 77ba71f

Browse files
authored
Update Spiral Matrix - Leetcode 54.py
Simplified the solution using top, bottom, left and right pointers
1 parent c329092 commit 77ba71f

File tree

1 file changed

+36
-41
lines changed

1 file changed

+36
-41
lines changed
Lines changed: 36 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,41 @@
11
class Solution:
22
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
3+
res = []
4+
top,bottom = 0, len(matrix)-1
5+
left,right = 0, len(matrix[0])-1
86

9-
UP_WALL = 0
10-
RIGHT_WALL = n
11-
DOWN_WALL = m
12-
LEFT_WALL = -1
7+
while top<=bottom and left<=right:
138

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
9+
# Move left to right
10+
for i in range(left,right+1):
11+
res.append(matrix[top][i])
12+
13+
top+=1
14+
15+
# Move top to bottom
16+
for i in range(top,bottom+1):
17+
res.append(matrix[i][right])
18+
19+
right-=1
20+
21+
# Check If we can parse the row
22+
if top<=bottom:
23+
# Move right to left
24+
for i in range(right,left-1,-1):
25+
res.append(matrix[bottom][i])
26+
27+
bottom-=1
28+
29+
# Check If we can parse the col
30+
if left<=right:
31+
# Move bottom to top
32+
for i in range(bottom,top-1,-1):
33+
res.append(matrix[i][left])
34+
35+
left+=1
4336

44-
return ans
45-
# Time: O(m*n)
46-
# Space: O(1)
37+
return res
38+
39+
40+
# Time Complexity: 𝑂(𝑚×𝑛)
41+
# Space Complexity: 𝑂(𝑚×𝑛)

0 commit comments

Comments
 (0)