Skip to content

Commit 52dfd63

Browse files
committed
Week 15: Rotate Image Solution
1 parent 342f8d8 commit 52dfd63

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

rotate-image/doh6077.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# https://leetcode.com/problems/rotate-image/
2+
# 48. Rotate Image
3+
class Solution:
4+
def rotate(self, matrix: List[List[int]]) -> None:
5+
"""
6+
Do not return anything, modify matrix in-place instead.
7+
"""
8+
# First Try - Thought process:
9+
# group values by column index (j) to rebuild rows
10+
# Brute force: create an extra 2D matrix and then copy it back into matrix
11+
# Needs optimization: this approach uses extra space
12+
matrix_result = [[] for _ in range(len(matrix))]
13+
for i in reversed(matrix):
14+
for j, value in enumerate(i):
15+
matrix_result[j].append(value)
16+
for r in range(len(matrix)):
17+
matrix[r] = matrix_result[r]
18+
19+
# Youtube Solution - Transpose Operation + hr
20+
# Swap i, js
21+
n = len(matrix)
22+
for i in range(n):
23+
for j in range(i + 1, n):
24+
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
25+
26+
# Reflection
27+
for i in range(n):
28+
for j in range(n // 2):
29+
matrix[i][j], matrix[i][n - j - 1] = matrix[i][n - j - 1], matrix[i][j]

0 commit comments

Comments
 (0)