Matrix Layer Rotation

Matrix Layer Rotation


You are given a 2D matrix of dimension and a positive integer . You have to rotate the matrix times and print the resultant matrix. Rotation should be in anti-clockwise direction.

Rotation of a matrix is represented by the following figure. Note that in one rotation, you have to shift elements by one step only.

Matrix Rotation

Matrix Rotation

Read more on the challenge page…

My Solution

I’m providing the solution for Python and JS, please leave on the comments if you found a better way.

I really got the solution inspired by the image on the problem statement above. The idea is to resolve one “layer” at a time.

For each layer I’m building a flat array with the elements assigned to the correct position as it’s easier to do this on 1 dimension. After I complete the array, I then proceed to recreate the matrix layer from it.

The problem was actually quite simple to solve, though it looks messy.

I like using variables to define the direction where I’m going while looping through the matrix layer, though some solutions for problems like this usually don’t use this directional variables, but multiple loops instead. anyway works.

Here is my solution as always for Python and JS


Subscribe to my weekly newsletter for developers and builders and get a weekly email with relevant content.

    You can learn more about what to expect in these emails here.