--- title: "#48 Rotate Image" tags: LeetCode, Top100 --- #48 Rotate Image == 題目描述 -- You are given an *n x n* 2D ==matrix== representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image ==**in-place**==, which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation. Example 1: -- ![](https://i.imgur.com/Vmw8Ltu.png) >Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [[7,4,1],[8,5,2],[9,6,3]] 解題思維 -- 如果照著題目意思轉90度,很難完成in-place的要求。 我們仔細觀察矩陣位置,發現:如果我們先將其矩陣上下顛倒 >[[7,8,9],[4,5,6],[1,2,3]] 再對角線交換,也能達到90度旋轉。 Logic -- ```python= class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ matrix.reverse() n = len(matrix) for i in range(n): for j in range(i, n): if i == j: continue matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] ```