-
Notifications
You must be signed in to change notification settings - Fork 0
/
MatrixRotation.py
47 lines (44 loc) · 1.83 KB
/
MatrixRotation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
def rotateMat(N,M,l,rot,rin,mat):
# rotate each layer
for level in range(l):
r = rot % len(rin[level])
rin[level] = rin[level][r:] + rin[level][:r]
# fill the array with the rotated elements
for level in range(l):
top = (N-1) - 2 * level
side = (M-1) - 2 * level
for i in range(top):
mat[level][level + i] = rin[level].pop(0) # right
for j in range(side):
mat[level + j][level + top] = rin[level].pop(0) # down
for i in range(top):
mat[level + side][level + top - i] = rin[level].pop(0) # left
for j in range(side):
mat[level + side - j][level] = rin[level].pop(0) # up
def flatRings(M,N,mat,rot):
# flatten the rings into a list
l = int(min(N, M)/2)
rin = [[] for lay in range(l)]
for level in range(l):
top = (N-1) - 2 * level
side = (M-1) - 2 * level
for i in range(top): # right
rin[level].append(mat[level][level + i])
for j in range(side): # down
rin[level].append(mat[level + j][level + top])
for i in range(top): # left
rin[level].append(mat[level + side][level + top - i])
for j in range(side): # up
rin[level].append(mat[level + side - j][level])
rotateMat(N,M,l,rot,rin,mat)
# input
M, N, rot = map(int, input().split())
mat = []
for i in range(M):
mat.append(list(map(int, input().split())))
flatRings(M,N,mat,rot)
# print the rotated matrix
for row in range(M):
for col in range(N):
print(mat[row][col], "", end="")
print()