Answer to Question #180105 in Python for mani

Question #180105

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.




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-04-10T22:10:48-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:

        prev = mat[top + 1][left]

        for i in range(left, right + 1):
            curr = mat[top][i]
            mat[top][i] = prev
            prev = curr

        top += 1


        for i in range(top, bottom + 1):
            curr = mat[i][right]
            mat[i][right] = prev
            prev = curr

        right -= 1

        for i in range(right, left - 1, -1):
            curr = mat[bottom][i]
            mat[bottom][i] = prev
            prev = curr

        bottom -= 1


        for i in range(bottom, top - 1, -1):
            curr = mat[i][left]
            mat[i][left] = prev
            prev = curr

        left += 1

    return mat


# Utility Function
def printMatrix(mat):
    for row in mat:
        print(row)
matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16]
]
"""
matrix =[
         [1, 2, 3],
         [4, 5, 6],
         [7, 8, 9]
      ]
"""

matrix = rotateMatrix(matrix)
printMatrix(matrix)

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