Looking for good programming challenges?

Use the search below to find our solutions for selected questions!

Rotate Matrix / Image challenge

Sharing is caring!

Problem statement
You are given an n \times n 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 \lfloor\dfrac{n}{2}\rfloor layers. We then iterate of the length of each layer and shift our matrix cells, side for side:

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

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()