Given an n × n represents a two-dimensional matrix image. The image is rotated 90 degrees clockwise.
Description:
You have to rotate the image in place, which means you need to directly modify the two-dimensional matrix input. Do not use another matrix to rotate an image.
Example 1:
Given = Matrix
[
[l, 2,3],
[4,5,6],
[7,8,9]
],
In situ rotation of the input matrix, so that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 2:
Given = Matrix
[
[. 5,. 1, 9,11],
[2,. 4, 8,10],
[13 is,. 3,. 6,. 7],
[15,14,12,16]
],
In situ rotation of the input matrix, so that it becomes:
[
[15, 13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7, 10 ]
]
Nothing to say, remember the routine rotation matrix, we first conduct a diagonal axis flip (transpose), then once again to the vertical axis of the center line of the shaft can be reversed. Time complexity of this approach is O (n ^ 2), the spatial complexity is O (1)
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, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# 再做以竖轴中心线为轴的翻转
for i in matrix:
i.reverse()