Skip to content

Commit daca0d3

Browse files
committed
problem: 0048 rotate image
1 parent d5aea89 commit daca0d3

File tree

5 files changed

+104
-0
lines changed

5 files changed

+104
-0
lines changed
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
# 0048. Rotate Image
2+
3+
- Difficulty: medium
4+
- Link: https://leetcode.com/problems/rotate-image/
5+
- Topics: Array-String, Matrix
6+
7+
# Clarification
8+
9+
1. Check the inputs and outputs
10+
- INPUT: List[List[int]]
11+
- OUTPUT: List[List[int]]
12+
2. Check the main goal
13+
- You have to rotate the image **[in-place](https://en.wikipedia.org/wiki/In-place_algorithm)**
14+
15+
# Naive Solution
16+
17+
### Thought Process
18+
19+
1. 定義 matrix 邊界,設定上下左右邊界
20+
2. 由左上開始 rotate
21+
22+
![Untitled](./Untitled.png)
23+
24+
- Rotate 的方式
25+
26+
![Untitled](./Untitled%201.png)
27+
28+
- Implement
29+
30+
```python
31+
class Solution:
32+
def rotate(self, matrix: List[List[int]]) -> None:
33+
"""
34+
Do not return anything, modify matrix in-place instead.
35+
"""
36+
left = 0
37+
right = len(matrix[0]) - 1
38+
39+
while left < right:
40+
for i in range(0, right - left):
41+
top, bottom = left, right
42+
left_top = matrix[top][left + i]
43+
matrix[top][left + i] = matrix[bottom - i][left]
44+
matrix[bottom - i][left] = matrix[bottom][right - i]
45+
matrix[bottom][right - i] = matrix[top + i][right]
46+
matrix[top + i][right] = left_top
47+
left += 1
48+
right -= 1
49+
```
50+
51+
52+
### Complexity
53+
54+
- Time complexity: $O(n^2)$
55+
- Space complexity: $O(1)$
56+
57+
### Problems & Improvement
58+
59+
- 多個位置轉換,需抓出好的基準點 (例如 boundary ),較不易混淆
60+
61+
# Improvement
62+
63+
### Thought Process
64+
65+
1. 轉置矩陣
66+
2. reverse column
67+
68+
![Untitled](./Untitled%202.png)
69+
70+
- 交換的方式
71+
72+
![Untitled](./Untitled%203.png)
73+
74+
- Implement
75+
76+
```python
77+
class Solution:
78+
def rotate(self, matrix: List[List[int]]) -> None:
79+
"""
80+
Do not return anything, modify matrix in-place instead.
81+
"""
82+
lenCol = len(matrix)
83+
for i in range(0, lenCol):
84+
for j in range(i + 1, lenCol):
85+
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
86+
87+
for i in range(0, lenCol):
88+
for j in range(0, lenCol // 2):
89+
matrix[i][j], matrix[i][lenCol - 1 -j] = matrix[i][lenCol - 1 -j], matrix[i][j]
90+
```
91+
92+
93+
### Complexity
94+
95+
- Time complexity: $O(n^2)$
96+
- Space complexity: $O(1)$
97+
98+
# Check special cases, check error
99+
100+
-
101+
102+
# Note
103+
104+
- [Rotate Image - Matrix - Leetcode 48](https://www.youtube.com/watch?v=fMSJSS7eO1w)

0048 Rotate Image/Untitled 1.png

217 KB
Loading

0048 Rotate Image/Untitled 2.png

326 KB
Loading

0048 Rotate Image/Untitled 3.png

351 KB
Loading

0048 Rotate Image/Untitled.png

409 KB
Loading

0 commit comments

Comments
 (0)