Teaching Kids Programming – Rotate a 2D Matrix/Image 90 Degree Anti-Clockwise


Teaching Kids Programming: Videos on Data Structures and Algorithms

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (Anti-clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

We have talked about Teaching Kids Programming – Rotate a 2D Matrix/Image 90 Degree Clockwise – which is based on two steps – transposing the matrix/image and then reverse each rows.

Algorithm to Rotate a 2D Matrix/Image 90 Degree Clockwise

To perform an anticlockwise – we can actually conduct there clockwise rotations. Alternatively, after matrix/image transpose, we can reverse the entire rows aka first row with the last row, the second row with the second-last row ..

1
2
3
4
5
def rotateAntiClockwise(matrix):
    matrix[:] = transpose(matrix)
        R = len(matrix)
        for i in range(R//2):
            matrix[i], matrix[R - i - 1] = matrix[R - i - 1], matrix[i]
def rotateAntiClockwise(matrix):
    matrix[:] = transpose(matrix)
        R = len(matrix)
        for i in range(R//2):
            matrix[i], matrix[R - i - 1] = matrix[R - i - 1], matrix[i]

The time complexity is O(RC) and the space complexity is O(RC) although we can do this inplace if the R=C.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
313 words
Last Post: GoLang: Check If N and Its Double Exist (Hash Map)
Next Post: GoLang: Breadth First Search Algorithm to Compute the Deepest Leaves Sum of Binary Tree

The Permanent URL is: Teaching Kids Programming – Rotate a 2D Matrix/Image 90 Degree Anti-Clockwise

Leave a Reply