Skip to content

Commit dd4490d

Browse files
committed
problem: 0054 spiral matrix
1 parent eb381a4 commit dd4490d

File tree

2 files changed

+111
-0
lines changed

2 files changed

+111
-0
lines changed
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
# 0054. Spiral Matrix
2+
3+
- Difficulty: medium
4+
- Link: https://leetcode.com/problems/spiral-matrix/
5+
- Topics: Array-String, Matrix
6+
7+
# Clarification
8+
9+
1. Check the inputs and outputs
10+
- INPUT: List[List[int]]
11+
- OUTPUT: List[int]
12+
2. Check the main goal
13+
- traversal the matrix in spiral order
14+
15+
```
16+
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
17+
Output: [1,2,3,6,9,8,7,4,5]
18+
```
19+
20+
![Untitled](./Untitled.png)
21+
22+
23+
# Naive Solution
24+
25+
### Thought Process
26+
27+
1. the direction sequence is right → down → left → up
28+
2. boundary Left, right, top, bottom
29+
1. go through and shrink the boundary
30+
- Implement
31+
32+
```python
33+
class Solution:
34+
35+
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
36+
"""
37+
1. the direction sequence is right → down → left → up
38+
2. boundary Left, right, top, bottom
39+
- go through and shrink the boundary
40+
"""
41+
42+
result = []
43+
44+
left = 0
45+
right = len(matrix[0])
46+
top = 0
47+
bottom = len(matrix)
48+
49+
j = top
50+
while left < right and top < bottom:
51+
52+
#right
53+
for i in range(left, right):
54+
result.append(matrix[top][i])
55+
top += 1
56+
57+
# down
58+
for j in range(top, bottom):
59+
result.append(matrix[j][right - 1])
60+
right -= 1
61+
62+
if not (left < right and top < bottom):
63+
break
64+
65+
# left
66+
for i in range(right - 1, left -1, -1):
67+
result.append(matrix[bottom - 1][i])
68+
bottom -= 1
69+
70+
# up
71+
for j in range(bottom - 1, top - 1, -1):
72+
result.append(matrix[j][left])
73+
left += 1
74+
75+
return result
76+
```
77+
78+
79+
### Complexity
80+
81+
- Time complexity: $O(m*n)$
82+
- Space complexity:$O(m*n)$
83+
84+
### Problems & Improvement
85+
86+
-
87+
88+
# Improvement
89+
90+
### Thought Process
91+
92+
1.
93+
- Implement
94+
95+
```python
96+
97+
```
98+
99+
100+
### Complexity
101+
102+
- Time complexity:
103+
- Space complexity:
104+
105+
# Check special cases, check error
106+
107+
-
108+
109+
# Note
110+
111+
- [Spiral Matrix - Microsoft Interview Question - Leetcode 54](https://www.youtube.com/watch?v=BJnMZNwUk1M)

0054 Spiral Matrix/Untitled.png

15.3 KB
Loading

0 commit comments

Comments
 (0)