'''
leetcode 48 Rotate Image
给定n*n的二维图像,代表一张图像,将原始图像顺时针旋转90度
必须是in-place的操作,不允许额外分配内存空间再旋转二维数组
给定输入矩阵:
[
[1,2,3],
[4,5,6],
[7,8,9]
],
希望输出
[
[7,4,1],
[8,5,2],
[9,6,3]
]
算法1:
首先对原始的二维矩阵进行转置,得到
[
[1,4,7],
[2,5,8],
[3,6,9]
]
即交换二维数组中的元素,swap(array[i][j],array[j][i])
再交换转置数组每列的元素
但是这样带来的时间复杂度是O(n**2)
'''
class Solution:
def rotate(self, matrix) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
row=len(matrix)#求出矩阵的行数
col=len(matrix[0])# 求出矩阵的列数
# print(matrix)
for i in range(row):
for j in range(i+1,col):
temp=matrix[i][j]
print(i,j,matrix[i][j])
matrix[i][j]=matrix[j][i]
matrix[j][i]=temp
new_row=len(matrix)
new_col=len(matrix[0])
for i in range(row):
for j in range(new_col//2):
temp=matrix[i][j]
matrix[i][j]=matrix[i][new_col-j-1]
matrix[i][new_col - j - 1]=temp
# print(matrix)
if __name__=="__main__":
matrix=[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
]
Solution().rotate(matrix)
'''
算法2:
每次改变的是二维矩阵中最外面一圈的元素数值,由于顺时针旋转90度实际上只是对于每一层的元素数值存在交换操作
而层与层之间的元素数值并没有交换,故而设定4个指针,用于记录当前所处层的位置
比如对于4*4的矩阵,初始时,四个哨兵的数值分别为:
top=0 left=0 right=col bottom=row
首先对最外面一层的元素进行交换
'''
class Solution:
def rotate(self, matrix) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n=len(matrix)
top=0
left=0
bottom=n-1
right=n-1
while(bottom-top>0):
for i in range(top,bottom):
temp=matrix[i][right]
matrix[i][right]=matrix[top][i]
matrix[top][i]=matrix[n-i-1][left]
matrix[n - i - 1][left]=matrix[bottom][n-i-1]
matrix[bottom][n - i - 1]=temp
bottom-=1
right-=1
top+=1
left+=1
# print('here',matrix)
if __name__=="__main__":
matrix=[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
]
Solution().rotate(matrix)