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 K elements.
Sample input:
3 4
1 2 3 4
10 11 12 5
9 8 7 6
2
Sample output:
9 10 1 2
8 11 12 3
7 6 5 4
def replace_arr(arr, k):
return arr[-k:] + arr[:-k]
def rotete_rings(matrix, r):
tmp = []
k = 0
l = 0
m = len(matrix)
n = len(matrix[0])
while (((n - k) > 0) and ((m - l) > 0)):
for i in range(k,n):
tmp.append(matrix[k][i])
for j in range(l+1,m):
tmp.append(matrix[j][n-1])
for i in range(n-2,k-1,-1):
tmp.append(matrix[m-1][i])
for j in range(m-2,l,-1):
tmp.append(matrix[j][k])
if len(tmp) <= r:
break
tmp = replace_arr(tmp,r)
c = 0
for i in range(k,n):
matrix[k][i] = tmp[c]
c += 1
for j in range(l+1,m):
matrix[j][n-1] = tmp[c]
c += 1
for i in range(n-2,k-1,-1):
matrix[m-1][i] = tmp[c]
c += 1
for j in range(m-2,l,-1):
matrix[j][k] = tmp[c]
c += 1
tmp = []
k += 1
l += 1
m -= 1
n -= 1
return matrix
m, n = input().split()
m, n = int(m), int(n)
matrix = [[int(i) for i in input().split()] for _ in range(m)]
k = int(input())
rotated_matr = rotete_rings(matrix, k)
for row in rotated_matr:
print(*row)
Comments
Leave a comment