Answer to Question #176681 in Python for G V S Bhasker Nikhil Patchipulusu

Question #176681

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.

For example, if the given M and N are 4 and 4 respectively. If the matrix elements are

1 2 3 4

5 6 7 8

9 10 11 12

13 14 15 16

If the given K is 3. Rotate each ring of the matrix by 3 elements.

In the above matrix, the elements (1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5) is a ring, similarly, the elements (6, 7, 11, 10) will make a ring.

Therefore, by rotating each ring in clockwise direction by 3 elements will give (13, 9, 5, 1, 2, 3, 4, 8, 12, 16, 15, 14) and (10, 6, 7, 11). So the output should be

13 9 5 1

14 7 11 2

15 6 10 3

16 12 8 4


1
Expert's answer
2021-03-29T14:59:31-0400
M = int(input("Enter M: "))
N = int(input("Enter N: "))
K = int(input("Enter K: "))
print("")
A = [[0]*N for x in range(M)]
x = 1
for i in range(0, M):
    for j in range(0, N):
        A[i][j] = x
        x += 1
for i in range(M):
    for j in range(N):
        print(A[i][j], end = "\t")
    print("")
 
Ring = (min(M, N) + 1) // 2
print(Ring)
 
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
    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
APPROVED BY CLIENTS