Rotate Matrix
January 27, 2023
Problem
Write a method to rotate an image by 90 degrees given an image represented by a NxN matrix, where each pixel in the image is 3 bytes (clockwise). Is it possible to do this in place?
For
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
the output should be
solution(a) = [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
Solution
The easiest way to rotate the matrix by 90 degrees clockwise is to implement the rotation in layers. Perform a circular rotation on each layer, moving the top edge to the right edget, the right edge to the bottom edge, the bottom edge to the left edge, and the left edge to the top edge.
How to perform four-way edge swap? Using copy between edge will require memory which actually unnecessary. To implement inplace rotation we only need 1 temporary and swapping by index instead of by values.
Code
Dry Run
Input:[[10,9,6,3,7], [6,10,2,9,7], [7,6,3,8,2], [8,9,7,9,9], [6,8,6,8,2]]Result Rotate Layer 06 8 7 6 10 8 10 2 9 9 6 6 3 8 6 8 9 7 9 3 2 9 2 7 7Result Rotate Layer 16 8 7 6 10 8 9 6 10 9 6 7 3 2 6 8 9 8 9 3 2 9 2 7 7Result Rotate Layer 26 8 7 6 10 8 9 6 10 9 6 7 3 2 6 8 9 8 9 3 2 9 2 7 7