Answer to Question #179762 in Python for adhi chinna

Question #179762

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


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

next M lines will contain N space-separated integers.

next line will contain an integer, denoting K.Output


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


For example, if the given M and N are 4 and 4 respectively.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). output should be

13 9 5 1

14 7 11 2

15 6 10 3

16 12 8 4


1
Expert's answer
2021-04-12T02:27:14-0400
import sys


M = input("Enter number of row: ")
N = input("Enter number of columns: ")
K = input("Enter number of elements to rotate clockwise: ")


cnt = 1
src = []
for i in range(M):
    row = []
    for j in range(N):
        row.append(cnt)
        cnt = cnt + 1
    src.append(row)

print("Before rotate:")
for i in range(M):
    print(str(src[i]))

rings = []
for i in range(min(M,N) // 2):    
    ring = []
    for j in range(i, N - i):
        ring.append(src[i][j])


    for j in range(i + 1, M - i - 1):
        ring.append(src[j][N - i - 1])


    for j in range(N - i - 1, i, -1):
        ring.append(src[M - i - 1][j])


    for j in range(M - i - 1, i, -1):
        ring.append(src[j][i])


    if K > len(ring):
        kk = (K % len(ring)) # // (i + 1)
        ring = ring[-kk:] + ring[:-kk]
    rings.append(ring)


for i in range(min(M,N) // 2):
    p = 0
    for j in range(i, N - i):
        src[i][j] = rings[i][p]
        p = p + 1


    for j in range(i + 1, M - i - 1):
        src[j][N - i - 1] = rings[i][p]
        p = p + 1


    for j in range(N - i - 1, i, -1):
        src[M - i - 1][j]  = rings[i][p]
        p = p + 1


    for j in range(M - i - 1, i, -1):
        src[j][i]  = rings[i][p]
        p = p + 1


print("After rotate:")
for i in range(M):
    print(str(src[i]))     

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