Answer to Question #180500 in Python for hemanth

Question #180500

Rotate Matrix Rings

Given a matrix of order M*N and a value K, write a program to rotate each ring of 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 M and N.

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

The next line will contain integer, denoting K.


Output


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




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

1 2 3 4

5 6 7 8

9 10 11 12

13 14 15 16

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

In 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 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-13T06:30:55-0400
m, n = input('Enter the size of the matrix m n ').split()
m = int(m)
n = int(n)
matrix =[]
for i in range(m):
    row = [int(x) for x in input(f'Enter the {i+1} string ').split()][:n]
    matrix.append(row)
k = int(input('Enter the number of rotation of the rings '))
rings_count = int(min(m,n)/2+ .5)
for i in range(rings_count):
    rings = []
    row ,col = i, i
    row_add, col_add = 0, 1
    while True:
        rings.append((row,col))
        if (col + col_add < i or 
        col + col_add > n-1-i or
        row + row_add < i or
        row + row_add > m-1-i):
            row_add, col_add =col_add, -row_add
        row += row_add
        col += col_add
        if row == i and col == i:
            break
        if (col  < i or col > n-1-i or
        row < i or row > m-1-i): 
            break
    if len(rings) <= k:
        break
    elem = []
    for i in rings:
        elem.append(matrix[i[0]][i[1]])
    elem = elem[-k:] + elem[:-k]
    for i in range(len(rings)):
        matrix[rings[i][0]][rings[i][1]] = elem[i]
#output 
for i in range(m):
    print(*matrix[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