Answer to Question #315060 in Python for CHINNI

Question #315060

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


1
Expert's answer
2022-03-21T06:50:16-0400
def read_matrix(n):
    M = []
    for i in range(n):
        row = [int(s) for s in input().split()]
        M.append(row)
    return M


def rotate(M, s):
    n = len(M)
    R = []
    for i in range(n):
        R.append([0]*n)


    if s == 270:
        for i in range(n):
            for j in range(n):
                R[i][j] = M[j][n-1-i]
    elif s == 180:
        for i in range(n):
            for j in range(n):
                R[n-1-i][n-1-j] = M[i][j]
    elif s == 90:
        for i in range(n):
            for j in range(n):
                R[i][j] = M[n-1-j][i]
    return R


def update(M, i, j, v):
    n = len(M)
    U = [ M[i][:] for i in range(n)]
    U[i][j] = v
    return U


def query(M, i, j):
    return M[i][j]


def main():
    n = int(input())
    M = read_matrix(n)

    while True:
        line = input()
        L = line.split()
        if L[0] == '-1':
            break
        if L[0] == 'R':
            s = int(L[1])
            M = rotate(M, s)
        elif L[0] == 'U':
            i = int(L[1])
            j = int(L[2])
            v = int(L[3])
            M = update(M, i, j, v)
        elif L[0] == 'Q':
            i = int(L[1])
            j = int(L[2])
            v = query(M, i, j)
            print(v)


main()

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS