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 in-place, 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]
]
其实就是顺时针旋转一个矩阵(等宽高)。
思路一、暴力求解
摸清楚规律就好:将矩形一圈一圈的旋转,从外向内伸进,添加一个padding,用来记录每一圈的位置。先将top旋转到right,再将right旋转到bottom,然后将bottom旋转到left,最后将left旋转到top
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
padding = 0
paddingEnd = 0
l = len(matrix)
if l%2 == 0:
paddingEnd = (int)(l/2)
else:
paddingEnd = (int)((l-1)/2)
for padding in range(paddingEnd):
for i in range(padding+1,l-padding):
# 1. top -> right
tmpRight = matrix[i][l-padding-1]
matrix[i][l-padding-1] = matrix[padding][i]
# 2. right -> bottom
tmpBottom = matrix[l-padding-1][l-1-i]
matrix[l-padding-1][l-1-i] = tmpRight
# 3. bottom -> left
tmpLeft = matrix[l-1-i][padding]
matrix[l-1-i][padding] = tmpBottom
# 4. left -> top
matrix[padding][i]=tmpLeft
print(matrix)
思路二
Discuss中的一种方法:先将数组取逆,再将对角线对称的两个元素互换。也可以得到正确结果。
class Solution:
# @param matrix, a list of lists of integers
# @return a list of lists of integers
def rotate(self, matrix):
matrix.reverse()
for i in range(len(matrix)):
for j in range(i):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
THE END.