Rotate Matrix Asked in: Google Facebook Amazon

 You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

You need to do this in place.

Note that if you end up using an additional array, you will only receive partial score.

Example:

If the array is

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

Then the rotated array becomes:

[
    [3, 1],
    [4, 2]
]
Solution:
class Solution:
    # @param A : list of list of integers
    # @return the same list modified
    def rotate(self, A):
        l = len(A)
        for i in range(l//2):
            A[i], A[l-i-1] = A[l-i-1], A[i]
        ans = [[A[j][i] for j in range(l)] for i in range(len(A[0]))]
        return ans


Screenshot:


Comments

Popular posts from this blog

Trouble with the Number System

Residue Arithmetic

Perfect Peak of Array