Rotate Image

Question

You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise).

Have you met this question in a real interview? Yes Example Given a matrix

[
    [1,2],
    [3,4]
]

rotate it by 90 degrees (clockwise), return

[
    [3,1],
    [4,2]
]

Challenge Do it in-place.

Thoughts

这一题比较直观,可以尝试画出类似坐标系找到规律,每一个rotate是四个点的位置转换 可以从最外层一圈rotate,逐渐往里边循环

注意点

  • 每个循环去掉外层的两行两列,所以行的循环应该指导n/2
  • 每个列的循环也要比上一个去掉两列

Solution

class Solution:
    """
    @param matrix: A list of lists of integers
    @return: Nothing
    """
    def rotate(self, matrix):
        # write your code here
        n = len(matrix)
        for i in range(n/2):
            for j in range(i, n-i-1):
                tmp = matrix[i][j]
                matrix[i][j] = matrix[n-1-j][i]
                matrix[n-1-j][i] = matrix[n-1-i][n-1-j]
                matrix[n-1-i][n-1-j] = matrix[j][n-1-i]
                matrix[j][n-1-i] = tmp