题目

给你一幅由 N × N 矩阵表示的图像,其中每个像素的大小为 4 字节。请你设计一种算法,将图像旋转 90 度。
不占用额外内存空间能否做到?

示例 1:
给定 matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],

原地旋转输入矩阵,使其变为:
[
[7,4,1],
[8,5,2],
[9,6,3]
]

示例 2:
给定 matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],

原地旋转输入矩阵,使其变为:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]

方案一(使用翻转代替旋转)

  1. class Solution:
  2. def rotate(self, matrix: List[List[int]]) -> None:
  3. """
  4. Do not return anything, modify matrix in-place instead.
  5. 使用翻转代替旋转
  6. """
  7. n = len(matrix)
  8. # 水平翻转
  9. for row in range(0, n // 2):
  10. matrix[row], matrix[n-row-1] = matrix[n-row-1], matrix[row]
  11. # 主对角线翻转
  12. for row in range(0, n):
  13. for col in range(row+1, n):
  14. matrix[row][col], matrix[col][row] = matrix[col][row], matrix[row][col]

原文

https://leetcode-cn.com/explore/learn/card/array-and-string/199/introduction-to-2d-array/1414/
https://leetcode-cn.com/problems/rotate-matrix-lcci/solution/xuan-zhuan-ju-zhen-by-leetcode-solution/