We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
def matrixRotation(matrix, r):
new_matrix = [[0] * n for _ in range(m)] # Init new matrix
# Solve it like onion, first start with the outside then dive one layer inside.
for k in range(min(m, n) // 2):
# Creating rotation path. Values are indices (row, col)
pos = [(i, k) for i in range(k, m - k)]
pos.extend([(m - 1 - k, i) for i in range(1 + k, n - k)])
pos.extend([(i, n - 1 - k) for i in range(m - 2 - k, -1 + k, -1)])
pos.extend([(k, i) for i in range(n - 2 - k, k, -1)])
length = len(pos)
for i in range(len(pos)):
# Find correct index after rotation.
idx = (i - r) % length
new_matrix[pos[i][0]][pos[i][1]] = matrix[pos[idx][0]][pos[idx][1]]
# Print the result.
for i in range(m):
print(' '.join(map(str, new_matrix[i])))
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Matrix Layer Rotation
You are viewing a single comment's thread. Return to all comments →
intuitive and short solution.
def matrixRotation(matrix, r): new_matrix = [[0] * n for _ in range(m)] # Init new matrix