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
input:4 4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
3
output should print like this:13 9 5 1
14 7 11 2
15 6 10 3
16 12 8 4
def RorateMatrix(A):
if(len(A)==0):
return
TopRow = 0
BottomRow = len(A)-1
LC = 0
RC = len(A[0])-1
while LC < RC and TopRow < BottomRow:
prev = A[TopRow+1][LC]
for i in range(LC, RC+1):
curr = A[TopRow][i]
A[TopRow][i] = prev
prev = curr
TopRow = TopRow + 1
for i in range(TopRow, BottomRow+1):
curr = A[i][RC]
A[i][RC] = prev
prev = curr
RC = RC - 1
for i in range(RC, LC-1, -1):
curr = A[BottomRow][i]
A[BottomRow][i] = prev
prev = curr
BottomRow = BottomRow - 1
for i in range(BottomRow, TopRow-1, -1):
curr = A[i][LC]
A[i][LC] = prev
prev = curr
LC = LC + 1
return A
# Utility Function
def DispMatrix(A):
for r in A:
print(r)
#Case-1
M=4
N=4
K=3
matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
print("Case-1: Sample Input-1")
DispMatrix(matrix)
A = matrix
for n in range(0,K):
A = RorateMatrix(A)
print("Sample Output-1")
DispMatrix(A)
#Case-2
M=3
N=4
K=2
matrix = [[1,2,3,4],[10, 11, 12, 5],[9,8,7,6]]
print("\n\nCase-2: Sample Input-2")
DispMatrix(matrix)
A = matrix
for n in range(0,K):
A = RorateMatrix(A)
print("Sample Output-2")
DispMatrix(A)
Comments
Leave a comment