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
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.
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 j will grab the columns. So when i = 0, j 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 i has increased to 2. At this moment the last item in the first row, 9 (matrix), is swapped with the first item in the last row, 1 (matrix).
Are you seeing the pattern now? And so it continues.
After a bit more swaps, we return the new matrix and print
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.
Here is my video tutorial below. I used a white paper. No board sorry.
2 Comments Add yours
I love your explanation.
LikeLiked by 1 person
Thank you so much. Glad you found it useful.