Saturday, May 17, 2014

Leetcode (python): rotate image



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?

Solution

This problem logic is easy, we have only to be careful with the position index.  For instance,
1     2     3     4
5     6     7     8
9   10    11   12
13   14   15   16
We have marked in pink the elements that rotate for row 0, column 1.

class Solution:
    # @param matrix, a list of lists of integers
    # @return a list of lists of integers
    def rotate(self, matrix):
        for i in range(0, len(matrix)//2):
            for j in range(i, len(matrix)-1-i):
                temp = matrix[i][j]
                matrix[i][j] = matrix[len(matrix)-1-j][i]
                matrix[len(matrix)-1-j][i] = matrix[len(matrix)-1-i][len(matrix)-1-j]
                matrix[len(matrix)-1-i][len(matrix)-1-j] = matrix[j][len(matrix)-1-i]
                matrix[j][len(matrix)-1-i] = temp
        return matrix

1 comment :

  1. def rotate(self, mat):
    if not mat:
    return mat
    return [[row[i] for row in reversed(mat)] for i in range(len(mat[0]))]

    ReplyDelete