Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
def print_matrix(matrix):
for line in matrix:
print(' '.join(map(str, line)))
def empty(n, m):
matrix = []
for i in range(m):
matrix.append(['.'] * n)
return matrix
def rotate_layers(layers, r):
rotated_layers = []
for layer in layers:
r0 = r % len(layer)
rotated = layer[r0:] + layer[:r0]
return rotated_layers
def get_layer(n, m, matrix, k=0):
return sum((
[matrix[k][i] for i in range(k, n-k)],
[matrix[i][n-1-k] for i in range(k+1, m-1-k)],
[matrix[m-1-k][i] for i in range(n-1-k, k-1, -1)],
[matrix[i][k] for i in range(m-k-2, k, -1)]
), [])
def unpack(n, m, matrix):
return [get_layer(n, m, matrix, i) for i in range(min(n, m) // 2)]
def pack(n, m, layers):
matrix = empty(n, m)
for k in range(min(n, m) // 2):
nk = n - k * 2
mk = m - k * 2
layer = layers[k]
for i in range(nk):
matrix[k][k+i] = layer[i]
for i in range(mk-2):
matrix[k+i+1][n-k-1] = layer[nk+i]
for i in range(nk):
matrix[m-k-1][n-k-1-i] = layer[nk+mk-2+i]
for i in range(mk-2):
matrix[m-k-2-i][k] = layer[nk+mk-2+nk+i]
return matrix
if __name__ == '__main__':
mnr = input().rstrip().split()
m, n, r = map(int, mnr)
matrix = []
for _ in range(m):
matrix.append(list(map(str, input().rstrip().split())))
layers = unpack(n, m, matrix)
r_layers = rotate_layers(layers, r)
result = pack(n, m, r_layers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment