Rotate Image

Question

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?

Tags

  • Array

Thought

Algorithm:

  1. Transpose the matrix
  2. Reverse the order of the matrix

Code

class Solution(object):
    def rotate(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: void Do not return anything, modify matrix in-place instead.
        """
        n = len(matrix)
        if n == 0:
            return []
        for i in xrange(n):
            for j in xrange(n - i - 1):
                matrix[i][j], matrix[n - j - 1][n - i - 1] = matrix[n - j - 1][n - i - 1], matrix[i][j]
        matrix.reverse()

results matching ""

    No results matching ""