# Rotate Matrix / Image challenge

**Problem statement**

You are given an 2D matrix / array representing an image. Rotate matrix by 90 degrees (clockwise) in-place.

**Solution**

We will work through the matrix layers. The layers of a matrix are illustrated below in different colours:

There are a total of layers. We then iterate of the length of each layer and shift our matrix cells, side for side:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
for c in range(l, n-l-1): top = m[l][c] # left goes to top m[l][c] = m[n-1-c][l] # bottom goes to left m[n-1-c][l] = m[n-l-1][n-c-1] # right goes to bottom m[n-l-1][n-c-1] = m[c][n-l-1] # top goes to right m[c][n-l-1] = top |

We need to temporary store the element of the top side of a layer before we replace it because we are going to need it at the end of the circle `top <- left <- bottom <- right <- top`

. And thats it.

The full code is listed below.

**Full code**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import numpy as np class Solution(object): def rotate(self, m): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ n = len(m) for l in range(0,n//2): for c in range(l, n-l-1): top = m[l][c] # left goes to top m[l][c] = m[n-1-c][l] # bottom goes to left m[n-1-c][l] = m[n-l-1][n-c-1] # right goes to bottom m[n-l-1][n-c-1] = m[c][n-l-1] # top goes to right m[c][n-l-1] = top print(np.matrix(m)) def main(): solution = Solution() solution.rotate([[1]]) solution.rotate([[1,2],[3,4]]) solution.rotate([[1,2,3],[4,5,6],[7,8,9]]) solution.rotate([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]) solution.rotate([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20],[21,22,23,24,25]]) if __name__ == "__main__": main() |