Rotate Matrix 90 degrees Clockwise Python Program
ADVERTISEMENTS
Rotate matrix 90 degrees clockwise python program. In this program, you will learn how to rotate the matrix 90 degrees clockwise in python.
Matrix before Rotation
x1 y1 z1
x2 y2 z2
x3 y3 z3
Matrix after 90 degrees Clockwise Rotation
x3 x2 x1
y3 y2 y1
z3 z2 z1
Source Code
# Rotate Matrix 90 degrees Clockwise Python Program
# It's the function to rotate
# the matrix 90 degree clock-wise
def rotate90DegClockwise(arru, N):
pass
# It will traverse the each cycle
for i in range (int (N / 2)):
for j in range (i, int (N - i - 1)):
# It will swap elements of each cycle in clock-wise direction
temp = arru[i][j]
arru[i][j] = arru[N - 1 - j][i]
arru[N - 1 - j][i] = arru[N - 1 - i][N - 1 - j]
arru[N - 1 - i][N - 1 - j] = arru[j][N - 1 - i]
arru[j][N - 1 - i] = temp
# It's the function for printing the rotated matrix
def printMatrix(arru, N):
pass
for i in range (N):
print (end="\t")
for j in range (N):
print (arru[i][j], end="\t")
print (end="\n\n")
# This is the driven calculation of matrix rotation
arru = [
[13, 13, 17, 11],
[25, 26, 27, 28],
[39, 30, 31, 31],
[43, 44, 45, 46]
]
# This will print the matrix before rotation
print ("-----The input matrix before 90 degrees clock-wise rotation-----\n")
printMatrix(arru, 4)
# This function will be rotate each element clock-wise
rotate90DegClockwise(arru, 4)
# This will print the matrix after rotation
print ("\n-----The matrix after 90 degrees clock-wise rotation-----\n")
printMatrix(arru, 4)
Output
-----The input matrix before 90 degrees clock-wise rotation-----
13 13 17 11
25 26 27 28
39 30 31 31
43 44 45 46
-----The matrix after 90 degrees clock-wise rotation-----
43 39 25 13
44 30 26 13
45 31 27 17
46 31 28 11