Matrix Rotation Clockwise by shifting one element at a time in Python 3

Matrix Rotation Clockwise is the rotation of a given matrix in the clockwise direction. Here, in this method, the elements of the matrix are shifted by one place in order to achieve the rotated matrix.

                4 8 7
Let Matrix, A = 6 7 5
                3 2 6

After Rotating the Matrix,

    6 4 8
A = 3 7 7
    2 6 5

The image below shows the number of cycles it takes to rotate the matrix in the given method.

Matrix Rotation Clockwise
Read more here:
Rotation matrix

Let’s take a look at the code snippet:

PROGRAM:

def rotateMatrix(mat): #clockwise rotation of matrix where each element is shifted by one place 
    if not len(mat):
        return
    top = 0
    bottom = len(mat)-1
    left = 0
    right = len(mat[0])-1
    while(left < right and top < bottom):
        prev = mat[top+1][left]
        for i in range(left, right+1):
            curr = mat[top][i]
            mat[top][i] = prev
            prev = curr
        top += 1
        for i in range(top, bottom+1):
            curr = mat[i][right]
            mat[i][right] = prev
            prev = curr
        right -= 1
        for i in range(right, left-1, -1):
            curr = mat[bottom][i]
            mat[bottom][i] = prev
            prev = curr
        bottom -= 1
        for i in range(bottom, top-1, -1):
            curr = mat[i][left]
            mat[i][left] = prev
            prev = curr
        left += 1
    return mat
n=int(input("Enter Number of Rows of Square Matrix:"))
print("Enter Matrix Elements:")
matrix=[]
for i in range(n):
    l=[]
    for j in range(n):
        x=int(input())
        l.append(x)
    matrix.append(l)
print("The entered Matrix is:")
for i in range(n):
    for j in range(n):
        print(matrix[i][j],end=" ")
    print()
print("The Matrix after rotation:")
matrix=rotateMatrix(matrix)
for i in range(n):
    for j in range(n):
        print(matrix[i][j],end=" ")
    print()

OUTPUT 1:

Enter Number of Rows of Square Matrix:3
Enter Matrix Elements:
4
5
7
8
9
6
4
3
2
The entered Matrix is:
4 5 7 
8 9 6 
4 3 2 
The Matrix after rotation:
8 4 5 
4 9 7 
3 2 6

OUTPUT 2:

Enter Number of Rows of Square Matrix:4
Enter Matrix Elements:
4
5
8
7
6
2
1
5
6
4
5
3
2
1
8
9
The entered Matrix is:
4 5 8 7 
6 2 1 5 
6 4 5 3 
2 1 8 9 
The Matrix after rotation:
6 4 5 8 
6 4 2 7 
2 5 1 5 
1 8 9 3

Also Read:

Leave a Reply

Your email address will not be published. Required fields are marked *