Matrix Rotation
You're given a square matrix A of dimentions N X n. You need to apply below 3 operations.
Rotation: It is represented as R S where S is an integer in {90,180,270...} which denotes the number of degrees to rotate .You need to rotate the matrix A by angle S in the clockwise direction.
The angle of rotation S will always be in multiples of 90 degrees.
Update: It is represented as U X Y Z. In initial matrix A , you need to update the element at row index X and column index Y with value Z.
Querying: It is represented as Q K L.You need to print the value at row index K and column index L of the matrix of the matrix A.
Sample Input 1
2
1 2
R 90
Q 0 0
Q 0 1
R 90
Q 0 0
U 0 0 6
Q 1 1
-1
Sample Output 1
3
1
4
6
Sample Input 2
2
5 6
7 8
R 90
Q 0 1
R 270
Q 1 1
R 180
U 0 0 4
Q 0 0
-1
Sample Output 2
5
8
8
def Query(Q,K,L):
return(Q[K][L])
def UpdateVal(U,X,Y,Z):
U[X][Y]=Z
return(U)
#Array matrix rotation
def Rotate(Arr,Angle):
A = int(Angle/90)
for n in range(0,A):
M = len(Arr[0])
for i in range(M // 2):
for j in range(i, M - i - 1):
t = Arr[i][j]
Arr[i][j] = Arr[M - 1 - j][i]
Arr[M - 1 - j][i] = Arr[M - 1 - i][M - 1 - j]
Arr[M - 1 - i][M - 1 - j] = Arr[j][M - 1 - i]
Arr[j][M - 1 - i] = t
return(Arr)
arr = [ [ 1, 2, 3, 4 ],
[ 5, 0, 7, 8 ],
[ 9, 10, 11, 12 ],
[ 103, 104, 105, 106 ] ]
S=[90,180,270,360]
print("Input Array:")
N = len(arr[0])
for i in range(0,N):
for j in range(0,N):
print(arr[i][j],end=" ")
print()
for r in range (0,len(S)):
NewArr = Rotate(arr,S[r])
print("Rotated Array at an angle = %d:"%S[r])
for i in range(0,N):
for j in range(0,N):
print(NewArr[i][j],end=" ")
print()
print("\n")
print("\Input Array:")
N = len(arr[0])
for i in range(0,N):
for j in range(0,N):
print(arr[i][j],end=" ")
print()
arr = UpdateVal(arr,2,1,20)
print("\nArray after updation: ")
for r in range(0,N):
for j in range(0,N):
print(arr[r][j],end=" ")
print()
for r in range (0,len(S)):
NewArr = Rotate(arr,S[r])
print("Rotated Array at an angle = %d:"%S[r])
for i in range(0,N):
for j in range(0,N):
print(NewArr[i][j],end=" ")
print()
print("\n")
print("\nQuerying Result:")
print(Query(arr,2,2))
Comments
Leave a comment