题目链接:https://leetcode.cn/problems/rotate-matrix-lcci/description/
给你一幅由 N × N 矩阵表示的图像,其中每个像素的大小为 4 字节。请你设计一种算法,将图像旋转 90 度。
不占用额外内存空间能否做到?
先转置再逆序
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
row, col = len(matrix), len(matrix[0])
for i in range(row):
for j in range(i, col):
tmp = matrix[i][j]
matrix[i][j] = matrix[j][i]
matrix[j][i] = tmp
for i in range(row):
matrix[i] = matrix[i][::-1]
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
n = len(matrix)
for i in range(n // 2):
for j in range((n+1) // 2):
matrix[i][j], matrix[n - j - 1][i], matrix[n - i - 1][n - j - 1], matrix[j][n - i - 1] \
= matrix[n - j - 1][i], matrix[n - i - 1][n - j - 1], matrix[j][n - i - 1], matrix[i][j]