Problem:
You are given an n x n 2D matrix representing an image.Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
利用处于中心的极坐标变换:
(r′t,θ′t)=(r,θ−π/2)
x′=x−(n−1)/2
y′=(n−1)/2−y
x′t=rtcos(θ−π/2)=y′
xt=n−1−y
注意 n <script type="math/tex" id="MathJax-Element-274">n</script>的奇偶影响即可。
__author__ = 'burger'
class Solution:
# @param {integer[][]} matrix
# @return {void} Do not return anything, modify matrix in-place instead.
def rotate(self, matrix):
n = len(matrix)
for i in range((n +1)//2):
for j in range(n//2):
tmp = 0
x = i
y = j
xt = y
yt = n - x - 1
last = matrix[x][y]
for l in range(4):
tmp = matrix[xt][yt]
matrix[xt][yt] = last
x = yt
y = n - xt - 1
xt = x
yt = y
last = tmp
if __name__ == '__main__':
s = Solution()
n = [[1,2],[3,4]]
m = [[1,2,3],[4,5,6],[7,8,9]]
s.rotate(n)
print(n)