Answer to Question #211087 in Python for raj

Question #211087


Given a matrix of order M*N and a value K, write a program to rotate each ring of the matrix clockwise by K elements. If in any ring has less than or equal to K elements, then don’t rotate that ring.Input


The first line of input will be two space-separated integers, denoting the M and N.

The next M lines will contain N space-separated integers.

The next line will contain an integer, denoting K.Output


The output should be M*N matrix by rotating the matrix by K elements.Explanation


Sample Input 1

4 4

1 2 3 4

5 6 7 8

9 10 11 12

13 14 15 16

3

Sample Output 1

13 9 5 1

14 7 11 2

15 6 10 3

16 12 8 4

Sample Input 2

3 4

1 2 3 4

10 11 12 5

9 8 7 6

2

Sample Output 2

9 10 1 2

8 11 12 3

7 6 5 4




1
Expert's answer
2021-06-27T14:09:51-0400
def RorateMatrix(A):
    if(len(A)==0):
        return
    TopRow = 0
    BottomRow = len(A)-1
    LC = 0
    RC = len(A[0])-1
    while LC < RC and TopRow < BottomRow:
        prev = A[TopRow+1][LC]
        for i in range(LC, RC+1):
            curr = A[TopRow][i]
            A[TopRow][i] = prev
            prev = curr
        TopRow = TopRow + 1
        for i in range(TopRow, BottomRow+1):
            curr = A[i][RC]
            A[i][RC] = prev
            prev = curr
        RC = RC - 1
        for i in range(RC, LC-1, -1):
            curr = A[BottomRow][i]
            A[BottomRow][i] = prev
            prev = curr
        BottomRow = BottomRow - 1
        for i in range(BottomRow, TopRow-1, -1):
            curr = A[i][LC]
            A[i][LC] = prev
            prev = curr
        LC = LC + 1
 
    return A
 

def DispMatrix(A):
    for r in A:
        print(r)
 


'''
print("Enter the input as per format given in assignment:\n")
M, N = input().split(' ')
M, N = int(M), int(N)
matrix = []
for _ in range(M):
	row = [int(x) for x in input().split(' ')]
	matrix.append(row)
K = int(input())
'''
#Case-1
M=4
N=4
K=3
matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
print("Case-1: Sample Input-1")
DispMatrix(matrix)
A = matrix
for n in range(0,K):
    A = RorateMatrix(A)
print("Sample Output-1")
DispMatrix(A)


#Case-1
M=3
N=4
K=2
matrix = [[1,2,3,4],[10, 11, 12, 5],[9,8,7,6]]
print("\n\nCase-2: Sample Input-2")
DispMatrix(matrix)
A = matrix
for n in range(0,K):
    A = RorateMatrix(A)
print("Sample Output-2")
DispMatrix(A)




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