Rotate a Matrix In-Place (Python)


Hello everyone, I finally have version 2 of our Rotation d’une Matrice (Rotation of a Matrix) and it is in-place. Yep, so no extra space. This code and explanation is A Lot shorter than version 1. 

Version 2: Full Code

Screenshot 2018-10-18 at 4.22.25 PM

First we define a function, rotate, with an argument, matrix. In our sample call statement, matrix has 3 rows and 3 columns. Make sure you also are rotating with an NxN. We reverse the matrix so that our code goes from [[1,2,3],[4,5,6],[7,8,9]] to [[7,8,9], [4,5,6], [1,2,3]]. After this, we can transpose along the diagonal.

Screenshot 2018-10-18 at 4.22.59 PM

Next, we have our nested for loops. We iterate, i, in the range of 3 (the length of the matrix). i will grab the rows and will grab the columns. So when i = 0, will be 0, 1, and 2. 

Next, we begin swapping. Remember, the first row from the original matrix, will be turned into the last row of the new matrix. We are swapping simultaneously. First, we swap the second value in the first row, 8, of the reversed matrix with the first value of the second row, 4. Then i iterates again because j has reached the end of it’s range of 1. Now has increased to 2. At this moment the last item in the first row, 9 (matrix[0][2]), is swapped with the first item in the last row, 1 (matrix[2][0]). 

Are you seeing the pattern now? And so it continues.

Screenshot 2018-10-18 at 4.23.45 PM

After a bit more swaps, we return the new matrix and print

Screenshot 2018-10-18 at 4.24.24 PM

This should be our result. If you are still confused on how we got here. Take a pen and paper and follow my steps after you’ve reversed the matrix. Then notice the diagonal in the image below. The reversed matrix had 3 in the 7’s place, 8 in the 4’s place and 9 in the 1’s place. Just swap.

Screenshot 2018-10-17 at 1.56.45 PM


Here is my video tutorial below. I used a white paper. No board sorry.



2 Comments Add yours

  1. Atom Nart says:

    I love your explanation.

    Liked by 1 person

    1. Colorful says:

      Thank you so much. Glad you found it useful.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s