iT邦幫忙

0

解LeetCode的學習筆記Day48_Rotate Image

LFI 2025-11-08 23:24:01183 瀏覽
  • 分享至 

  • xImage
  •  

今天是紀錄LeetCode解題的第四十八天

第四十八題題目: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.

給定一個n * n的二維圖形matrix,將影像旋轉90度,必須原地進行旋轉,這表示必須直接修改輸入的二維矩陣,不要分配另一個矩陣進行旋轉

解題思路

以主對角線為主,把對應對角線的元素交換,以範例一來說,2、4交換,3、7交換,6、8交換,交換完之後再把每一列反轉,反轉完的陣列就是旋轉90度了

程式碼

class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        for i in range(len(matrix)):
            for j in range(i+1,len(matrix)):
                matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
        for row in matrix:
            row.reverse()

執行過程

https://ithelp.ithome.com.tw/upload/images/20251108/20179234P7HtkIB8hK.png


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言