Rotate Matrix Rings
Given 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
first line of input will be two space-separated integers, denoting the M and N.
next M lines will contain N space-separated integers.
next line will contain an integer, denoting K.Output
output should be M*N matrix by rotating the matrix by K element.Explanation
if the given M and N are 4 and 4 respectively. If the matrix elements
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
def print_matr():
global matr
for row in matr:
for el in row:
print(str(el) + " ", end='')
print()
print()
def rings_amount():
global rows, cols, k
for ring_num in range(min(rows,cols)//2):
if 2 * (rows + cols - 4 * ring_num) - 4 < k:
print('break')
return ring_num
else:
return ring_num + 1
def rotate_by_one(ring_num):
global matr, rows, cols
left = top = ring_num
right = cols - 1 - ring_num
bottom = rows - 1 - ring_num
temp = matr[ring_num][ring_num]
# left column
for row_pos in range(top,bottom):
matr[row_pos][left] = matr[row_pos+1][left]
#print_matr()
# bottom row
for col_pos in range(left,right):
matr[bottom][col_pos] = matr[bottom][col_pos+1]
#print_matr()
# right column
for row_pos in range(bottom,top,-1):
matr[row_pos][right] = matr[row_pos-1][right]
#print_matr()
# top row
for col_pos in range(right,left,-1):
matr[top][col_pos] = matr[top][col_pos-1]
matr[ring_num][ring_num+1] = temp
#print_matr()
rows = m = 4
cols = n = 4
k = 3
matr = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
res = [
[13, 9, 5, 1],
[14, 7, 11, 2],
[15, 6, 10, 3],
[16, 12, 8, 4]
]
ring_nums = rings_amount()
for _ in range(k):
for ring_num in range(ring_nums):
rotate_by_one(ring_num)
print_matr()
Comments
Leave a comment