Problem: Matrix Rotation
Rotate a n*n matrix 90 degrees in anti-clockwise direction.
Input: Matrix: 1 2 3 4 5 6 7 8 9 Output: 3 6 9 2 5 8 1 4 7
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 column elements of first row to its last row. In above example,
We are swapping elements 1 to 3, 4 to 6 and 7 to 9. The middle column 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(int(len(matrix)/2)):
for j in range(len(matrix)):
m[i][j], m[len(matrix)-1-i][j] = m[len(matrix)-1-i][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 90deg anti-clockwisefor i in range(int(n/2)): for j in range(n): m[i][j], m[n-1-i][j] = m[n-1-i][j], m[i][j] print(m)
Comments