File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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 ]
You can’t perform that action at this time.
0 commit comments