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:
13 9 5 1
14 7 11 2
15 6 10 3
16 12 8 4 there should be no space before starting index line by line
class MyMatrix :
def __init__(self, matrix) :
# Get the size of matrix
self.rows = len(matrix)
self.cols = len(matrix[0])
def change(self, matrix, row, col, index) :
data = matrix[row][col]
temp = 0
# bottom right to botoom left
i = col - 1
while (i >= index) :
temp = matrix[row][i]
matrix[row][i] = data
data = temp
i -= 1
# botoom left to top right
i = row - 1
while (i >= index) :
temp = matrix[i][index]
matrix[i][index] = data
data = temp
i -= 1
# top right to top left
i = index + 1
while (i <= col) :
temp = matrix[index][i]
matrix[index][i] = data
data = temp
i += 1
# top left to bottom right
i = index + 1
while (i <= row) :
temp = matrix[i][col]
matrix[i][col] = data
data = temp
i += 1
def rotate(self, matrix, size) :
row = self.rows
col = self.cols
occurrence = self.cols
if (row < col) :
occurrence = row
i = 0
while (i < int(occurrence / 2)) :
row -= 1
col -= 1
self.change(matrix, row, col, i)
i += 1
if (size > 1) :
self.rotate(matrix, size - 1)
# Display matrix elements
def show_data(self, matrix) :
i = 0
while (i < self.rows) :
j = 0
while (j < self.cols) :
print(" ", matrix[i][j], end = "")
j += 1
print("\n", end = "")
i += 1
print("\n", end = "")
def main() :
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())
obj = MyMatrix(matrix)
size = K
print("Before\n", end = "")
obj.show_data(matrix)
obj.rotate(matrix, size)
print("After rotate ring in ", size ," times\n", end = "")
obj.show_data(matrix)
if __name__ == "__main__":
main()
Comments
Leave a comment