Article Directory
topic
Given an n × n two-dimensional matrix represents an image.
Rotate the image 90 degrees clockwise.
Description:
You have to rotate the image in place, which means you need to directly modify the input two-dimensional matrix. Please do not use another matrix to rotate the image.
Example 1:
Given matrix = [[1,2,3], [4,5,6], [7,8,9] ],
Rotate the input matrix in place 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, 3, 6, 7],
[15,14,12,16] ],Rotate the input matrix in place so that it becomes: [[15,13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9],
[16, 7,10,11 ]]
Problem-solving ideas
Idea one-find the law
Find out the relationship (law) between these several index.
That is: 任意一个(i,j) , (j, n-i-1), (n-i-1, n-j-1), (n -j-1, i)
it is the exchange of numbers on these four index numbers.
Idea 2: Flip in place
Flip the entire array, and then swap the numbers on both sides according to the diagonal
Code
Find the pattern
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//2):
for j in range(i, n - i - 1):
matrix[i][j],matrix[j][n-i-1],matrix[n-i-1][n-j-1],matrix[n-j-1][i] = \
matrix[n-j-1][i], matrix[i][j],matrix[j][n-i-1],matrix[n-i-1][n-j-1]
Rotate in place
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
matrix[:] = matrix[::-1]
#print(matrix)
for i in range(0, n):
for j in range(i+1, n):
#print(i, j)
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]