Premiumlab  

https://leetcode.com/problems/rotate-image/#/description

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?

 

 

Sol 1:

 

class Solution(object):
    def rotate(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: void Do not return anything, modify matrix in-place instead.
        """
        # Time O(n^2) Space(1)
        n = len(matrix)
        # flip the matrix alongside the counter-diagonal
        for i in range(n):
            for j in range(n-i):
                self.swap(matrix, i, j, n - 1 - j, n - 1 - i)
        # flip alongside the horizontal center line
        for i in range(n/2):
            for j in range(n):
                self.swap(matrix, i, j, n - 1 - i, j)
                
    def swap(self, matrix, i, j, p, q):
        tmp = matrix[i][j]
        matrix[i][j] = matrix[p][q]
        matrix[p][q] = tmp

 

 

 

Sol 2 :

 

class Solution(object):
    def rotate(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: void Do not return anything, modify matrix in-place instead.
        """
        # Time O(n^2) Space(1)
        n = len(matrix)
        # flip alongside the horizontal center line
        for i in range(n/2):
            for j in range(n):
                self.swap(matrix, i, j, n - 1 - i, j)
        # flip the matrix alongside the diagonal
        for i in range(n):
            for j in range(i+1, n):
                self.swap(matrix, i, j, j,i)

                
    def swap(self, matrix, i, j, p, q):
        tmp = matrix[i][j]
        matrix[i][j] = matrix[p][q]
        matrix[p][q] = tmp

 

posted on 2017-07-24 21:11  Premiumlab  阅读(117)  评论(0编辑  收藏  举报