Answer to Question #197006 in Python for Hari nadh babu

Question #197006

Rotate Matrix Rings

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


Test case 1

Input:-

4 4

1 2 3 4

5 6 7 8

9 10 11 12

13 14 15 16

3

Output:-

13 9 5 1

14 7 11 2

15 6 10 3

16 12 8 4


Test case 2

Input:-

3 4

1 2 3 4

10 11 12 5

9 8 7 6

2

Output:-

9 10 1 2

8 11 12 3

7 6 5 4


We need all test cases can be came when code was run. I want exact outputs for all test cases








1
Expert's answer
2021-05-23T19:38:03-0400
M = int(input("Enter M: "))
N = int(input("Enter N: "))
 
A = [[0]*N for x in range(M)]
for i in range(0, M):
    for j in range(0, N):
        A[i][j] = int(input())
 
K = int(input("Enter K: "))
Ring = (min(M, N) + 1) // 2
 
count = 0
r = 0
d = 0
l = 0
u = 0
 
for i in range(Ring):
    size = 2*(M-2*i) + 2*(N-2*i) - 4
    if M-2*i == 1:
        size = N-2*i
    if N-2*i == 1:
        size = M-2*i
    if size == 0:
        size = 1
    if size <= K:
        continue
    B = [0] * size
    startX = i
    startY = i
    for r in range(i, N-i):
        B[count] = A[startX][r]
        count += 1
    for d in range(startY + 1, M-i):
        B[count] = A[d][r]
        count += 1
    l = r - 1
    if M-(2*i) > 1 and N-(2*i) > 1:
        while l >= i:
            B[count] = A[d][l]
            count += 1
            l -= 1
        u = d - 1
        while u >= i + 1:
            B[count] = A[u][l+1]
            count += 1
            u -= 1
    for t in range(K):
        temp = B[size - 1]
        j = size - 1
        while j != 0:
            B[j] = B[j-1]
            j -= 1
        B[0] = temp
    
    count = 0
    r = 0
    d = 0
    l = 0
    u = 0
 
    for r in range(i, N-i):
        A[startX][r] = B[count]
        count += 1
    for d in range(startY + 1, M-i):
        A[d][r] = B[count]
        count += 1
    l = r - 1
    if M-(2*i) > 1 and N-(2*i) > 1:
        while l >= i:
            A[d][l] = B[count]
            count += 1
            l -= 1
        u = d - 1
        while u >= i + 1:
            A[u][l+1] = B[count]
            count += 1
            u -= 1
    
    count = 0
    r = 0
    d = 0
    l = 0
    u = 0
 
print("")
for i in range(M):
    for j in range(N):
        print(A[i][j], end = "\t")
    print("")

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