# Matrix Layer Rotation

Contents

## Problem

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.

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

If you liked what you saw, please support my work!

Juan Cruz Martinez

Juan has made it his mission to help aspiring developers unlock their full potential. With over two decades of hands-on programming experience, he understands the challenges and rewards of learning to code. By providing accessible and engaging educational content, Juan has cultivated a community of learners who share their passion for coding. Leveraging his expertise and empathetic teaching approach, Juan has successfully guided countless students on their journey to becoming skilled developers, transforming lives through the power of technology.