I have problem in inner Loop. The output should be M*N matrix by rotating the matrix by K elements.
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
my Approach:
def matrixRotation(matrix,r):
m, n = len(matrix), len(matrix[0])
b = [[None]*n for _ in range(m)]
indices = []
for c in range(min(m,n)//2):
index = []
for i in range(c,n-c): index.append((c,i))
for i in range(c+1,m-1-c): index.append((i,n-1-c))
for i in range(c,n-c)[::-1]: index.append((m-1-c,i))
for i in range(1+c,m-1-c)[::-1]: index.append((i,c))
if not index:
break
indices.append(index)
rotated = []
for index in indices:
k = r%len(index)
rotated.append(index[-k:]+index[:-k])
for (x,y) in zip(indices,rotated):
for ((c,d),(e,f)) in zip(x,y):
b[c][d] = matrix[e][f]
return b
m,n = map(int,input().split())
matrix = [input().split() for i in range(m)]
r = int(input())
for i in matrixRotation(matrix,r):
print(*i)
for input:
3 4
1 2 3 4
10 11 12 5
9 8 7 6
2
output should be:
9 10 1 2
8 11 12 3
7 6 5 4
my output:
9 10 1 2
8 None None 3
7 6 5 4