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 ..
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) —
296 wordsLast 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