48 Rotate Image
阿新 • • 發佈:2018-12-05
""" 48. Rotate Image Medium 1115 100 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] ] Example 2: Given input matrix = [ [ 5, 1, 9,11], [ 2, 4, 8,10], [13, 3, 6, 7], [15,14,12,16] ], rotate the input matrix in-place such that it becomes: [ [15,13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7,10,11] ]"""
可以寫成O(1)的空間複雜度,當然時間複雜度還是O(N^2)
首先回顧一下高中的數學知識,二維座標系上的一點(m,n)順時針旋轉90度後坐標為(n,-m)
矩陣左上角座標(0,0),右下角座標(n-1, n-1),x軸向下,y軸向右,和我們平時看到的座標系只是旋轉了一下,
所以矩陣順時針旋轉和我們平時遇到的座標系順時針旋轉是相同的,高中時的知識仍然適用,
所以矩陣順時針是圍繞點((n-1)/2,(n-1)/2)旋轉的,
設矩陣內一點座標為(a,b),相對於軸心得座標是(a-(n-1)/2, b-(n-1)/2),
旋轉90度以後相對座標是(b-(n-1)/2, (n-1)/2-a)
所以矩陣內的絕對座標是(b,n-1-a)
再看矩陣裡的點q0,旋轉90度到了q1,再旋轉90度到了q2,再旋轉90度到了q3,再旋轉一次就會到達原點,
這四個相對應的點必須一起實現,必須將矩陣這樣均勻地分為4份,每四個對應的點分別在這四個區域內,方法很多,
我的方法是對於第i行:0<=i<n-1,取(i,j):i<=j<n-1-i
q0:(i,j)
q1:(j,n-1-i)
q2:(n-1-i,n-1-j)
q3:(n-1-j,i)
class Solution: def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ n = len(matrix) for i in range(0,(n-1)//2+1): for j in range(i,n-1-i): tmp= matrix[i][j] matrix[i][j], matrix[j][n-1-i], matrix[n-1-i][n-1-j], matrix[n-1-j][i] = matrix[n-1-j][i], matrix[i][j], matrix[j][n-1-i], matrix[n-1-i][n-1-j]
網上還有一種思路就是先上下翻轉再沿主對角線翻轉
(x,y)->(-x,y)->(y,-x)
class Solution: def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ matrix.reverse() n = len(matrix) for i in range(0,n): for j in range(i): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]