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.
Sample Input 1
4 4
1 2 3 4
5 6 7 8
7 8 9 10
11 12 13 14
3
Sample Output 1
13 9 5 1
14 7 11 2
15 6 10 3
16 12 8 4
M = int(input("Enter M: "))
N = int(input("Enter N: "))
K = int(input("Enter K: "))
print("")
A = [[0]*N for x in range(M)]
x = 1
for i in range(0, M):
for j in range(0, N):
A[i][j] = x
x += 1
for i in range(M):
for j in range(N):
print(A[i][j], end = "\t")
print("")
Ring = (min(M, N) + 1) // 2
print(Ring)
count = 0
r = 0
d = 0
l = 0
u = 0
for i in range(Ring):
size = 2*(M-2*i) + 2*(N-2*i) - 4
if M-2*i == 1:
size = N-2*i
if N-2*i == 1:
size = M-2*i
if size == 0:
size = 1
B = [0] * size
startX = i
startY = i
for r in range(i, N-i):
B[count] = A[startX][r]
count += 1
for d in range(startY + 1, M-i):
B[count] = A[d][r]
count += 1
l = r - 1
if M-(2*i) > 1 and N-(2*i) > 1:
while l >= i:
B[count] = A[d][l]
count += 1
l -= 1
u = d - 1
while u >= i + 1:
B[count] = A[u][l+1]
count += 1
u -= 1
for t in range(K):
temp = B[size - 1]
j = size - 1
while j != 0:
B[j] = B[j-1]
j -= 1
B[0] = temp
count = 0
r = 0
d = 0
l = 0
u = 0
for r in range(i, N-i):
A[startX][r] = B[count]
count += 1
for d in range(startY + 1, M-i):
A[d][r] = B[count]
count += 1
l = r - 1
if M-(2*i) > 1 and N-(2*i) > 1:
while l >= i:
A[d][l] = B[count]
count += 1
l -= 1
u = d - 1
while u >= i + 1:
A[u][l+1] = B[count]
count += 1
u -= 1
count = 0
r = 0
d = 0
l = 0
u = 0
print("")
for i in range(M):
for j in range(N):
print(A[i][j], end = "\t")
print("")
Comments
Leave a comment