You are viewing a single comment's thread. Return to all comments →
Not great solution, but works
def matrixRotation(matrix: list, r:int) -> None: temp_matrix = matrix.copy() columns = len(matrix[0]) rows = len(matrix) if columns == 1: for l in matrix: print(*l) else: result = [[0 for _ in range(columns)] for _ in range(rows)] all_layers = [] if rows == 1: all_layers.append(matrix[0]) elif rows > 1 and columns == 1: all_layers = temp_matrix else: for _ in range(min(rows, columns) // 2): temp, right, left = [],[],[] top = temp_matrix.pop(0) bottom = temp_matrix.pop()[::-1] for layer in temp_matrix: right.append(layer.pop()) left.append(layer.pop(0)) temp += top + right + bottom + left[::-1] all_layers.append(temp) if len(temp_matrix) == 1: all_layers.append(temp_matrix.pop()) for layer in all_layers: try: rotation_range = r % len(layer) except: rotation_range = r for _ in range(rotation_range): if layer: layer.append(layer.pop(0)) for i, layer in enumerate(all_layers): for idx in range(i, columns - i): result[i][idx] = layer.pop(0) for idx in range(1+i, (rows -1) - i): if len(result[idx]) == i or not layer: continue result[idx][-(1+i)] = layer.pop(0) for idx in range(i+1, columns +1 - i): try: result[-(1+i)][-idx] = layer.pop(0) except: pass for idx in range(rows-2-i, i, -1): try: result[idx][i] = layer.pop(0) except: pass for l in result: print(*l)
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 →
Not great solution, but works