---
# System prepended metadata

title: 48. Rotate Image
tags: [Leetcode, medium, python, array, Top 100 Liked Questions]

---

###### tags: `Leetcode` `medium` `array` `python` `Top 100 Liked Questions`

# 48. Rotate Image

## [題目連結:] https://leetcode.com/problems/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.

![](https://i.imgur.com/TKOxBA5.png)
![](https://i.imgur.com/fUOM7p0.png)

#### [圖片來源:] https://leetcode.com/problems/rotate-image/

## 解題想法:
* 題目要求將矩陣順時針轉90度
    * 要求in-place modify
    * 不用return
* 想法:
* ![](https://i.imgur.com/vUic00N.png)

## Python:
``` python=
class Solution(object):
    def rotate(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: None Do not return anything, modify matrix in-place instead.
        """
        #不能return 所以對於反轉矩陣
        #不能用matrix = matrix[::-1]
        #要用matrix.reverse()
        matrix.reverse()
        for i in range(len(matrix)):
            for j in range(i):
                matrix[i][j],matrix[j][i]=matrix[j][i],matrix[i][j]
        

if __name__ == '__main__':
    result = Solution()
    matrix = [[1,2,3],[4,5,6],[7,8,9]]
    result.rotate(matrix)
    print(matrix)
#Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
#Output: [[7,4,1],[8,5,2],[9,6,3]]
```