48. Rotate Image - cocoder39/coco39_LC GitHub Wiki

48. Rotate Image

Option 1 (preferred): 2 rounds of flip: vertical flip + symmetrically flip

1  2  3             
4  5  6
7  8  9

up side down

7  8  9            
4  5  6
1  2  3 

symmetrically flip

7  4  1            
8  5  2
9  6  3 
class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        n = len(matrix)
        
        for i in range(n // 2):
            for j in range(n):
                matrix[i][j], matrix[n-1-i][j] = matrix[n-1-i][j], matrix[i][j]
        
        
        for i in range(n):
            for j in range(i):
                matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]

Option 2:

1  2  3             
4  5  6
7  8  9

rotate following 4 blocks with using a temporary block. More details can be found in this post

1  2
3
6
8  9
4
7

Option 3: similar as option 2, but rotate each element in the block identified in option 2 rather than rotating the entire block, which has less memory usage