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
M, N = input().split()
M, N = int(M), int(N)
matrix = []
for _ in range(M):
row = [int(x) for x in input().split()]
matrix.append(row)
K = int(input())
values = matrix[0][:-1] + [x[-1] for x in matrix][:-1] + matrix[-1][::-1][:-1] + [x[0] for x in matrix][::-1][:-1]
values = values[-K:] + values[:-K]
output = matrix
idxs = [(0, j) for j in range(N)][:-1] + [(i, N - 1) for i in range(M)][:-1] + [(M - 1, j) for j in range(N)][::-1][:-1] + [(i, 0) for i in range(M)][::-1][:-1]
idx = 0
for i, j in idxs:
output[i][j] = values[idx]
idx += 1
for i in output:
pass
print(i)
Input:
4 4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
3
Output:
[13, 9, 5, 1]
[14, 6, 7, 2]
[15, 10, 11, 3]
[16, 12, 8, 4]
Here the inner ring is not rotating the given times sir
M, N = input().split()
M, N = int(M), int(N)
matrix = []
for _ in range(M):
row = [int(x) for x in input().split()]
matrix.append(row)
K = int(input())
values = []
k = 0
l = 0
while (((N - k) > 0) and ((M - l) > 0)) and ((N - k)*(M-l)) > K:
for i in range(k,N):
values.append(matrix[k][i])
for j in range(l+1,M):
values.append(matrix[j][N-1])
for i in range(N-2,k-1,-1):
values.append(matrix[M-1][i])
for j in range(M-2,l,-1):
values.append(matrix[j][k])
values = values[-K:] + values[:-K]
c = 0
for i in range(k,N):
matrix[k][i] = values[c]
c += 1
for j in range(l+1,M):
matrix[j][N-1] = values[c]
c += 1
for i in range(N-2,k-1,-1):
matrix[M-1][i] = values[c]
c += 1
for j in range(M-2,l,-1):
matrix[j][k] = values[c]
c += 1
values = []
k += 1
l += 1
M -= 1
N -= 1
for i in matrix:
print(i)
Comments
Leave a comment