Answer to Question #177139 in Python for CHANDRASENA REDDY CHADA

Question #177139

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


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-03-31T15:40:58-0400
def rotateMatrix(mat):

  

    if not len(mat):

        return

      

    " " "

        top : starting row index

        bottom : ending row index

        left : starting column index

        right : ending column index

    " " "

  

    top = 0

    bottom = len(mat)-1

  

    left = 0

    right = len(mat[0])-1

  

    while left < right and top < bottom:

  

        # Store the first element of next row,

        # this element will replace first element of

        # current row

        prev = mat[top+1][left]

  

        # Move elements of top row one step right

        for i in range(left, right+1):

            curr = mat[top][i]

            mat[top][i] = prev

            prev = curr

  

        top += 1

  

        # Move elements of rightmost column one step downwards

        for i in range(top, bottom+1):

            curr = mat[i][right]

            mat[i][right] = prev

            prev = curr

  

        right -= 1

  

        # Move elements of bottom row one step left

        for i in range(right, left-1, -1):

            curr = mat[bottom][i]

            mat[bottom][i] = prev

            prev = curr

  

        bottom -= 1

  

        # Move elements of leftmost column one step upwards

        for i in range(bottom, top-1, -1):

            curr = mat[i][left]

            mat[i][left] = prev

            prev = curr

  

        left += 1

  

    return mat

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