Problem: Matrix Rotation
Rotate a n*n matrix 90 degrees in clockwise direction.
Input:
Matrix:
1 2 3
4 5 6
7 8 9
Output:
7 4 1
8 5 2
9 6 3
Approach: The idea behind this is to first find the transpose of given matrix. Transpose of above matrix is:
1 4 7
2 5 8
3 6 9
Now, we have to swap same row elements of first column to its last column. In above example,
We are swapping elements 1 to 7, 2 to 8 and 3 to 9. The middle row of matrix is same as it is.
So, the condition we are using for transposing is:
for i in range(len(matrix)):
for j in range(i,len(matrix)):
m[i][j], m[j][i] = m[j][i], m[i][j]
Now, after transposing we are again doing swapping for the perfect answer.
for i in range(len(matrix):
for j in range(int(len(matrix)/2)):
m[i][j], m[i][len(matrix)-1-j] = m[i][len(matrix)-1-j], m[i][j]
Solution:
import numpy as np row = int(input("enter no of rows:")) col = int(input("enter no of columns:")) n = list(map(str, input().split(" "))) m = np.array(n).reshape(row,col) n= len(m)
#matrix transpose
for i in range(n): for j in range(i,n): m[i][j], m[j][i] = m[j][i], m[i][j]
#matrix rotation 90degrees clockwise
for i in range(n): for j in range(int(n/2)): m[i][j], m[i][n-1-j] = m[i][n-1-j], m[i][j] print(m)
Comments