本文共 937 字,大约阅读时间需要 3 分钟。
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image , which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Given input matrix = [ [1,2,3], [4,5,6], [7,8,9]],rotate the input matrix in-place such that it becomes:[ [7,4,1], [8,5,2], [9,6,3]]
将2D矩阵顺时针旋转90度。
可以先将矩阵沿对角线做对称变换
[[1, 4, 7],
[2, 5, 8],
[3, 6, 9]]
然后沿水平方向做轴对称即可。
class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ n = len(matrix) for i in range(n): for j in range(i+1): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] for i in range(n): for j in range(int(n/2)): matrix[i][j],matrix[i][n-j-1]= matrix[i][n-j-1], matrix[i][j]
转载地址:http://dcrbb.baihongyu.com/