今天是紀錄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()
