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.
My Python3 solution. The rationale is that for each onion layer:
1. Get a list of coordinates on this layer (dst)
2. Rotate this list of coordinates to make a new list (src)
3. For each coordinate in dst, set the value of this coordinate in the output matrix to the value of the corresponding src coordinate in the original matrix
defget_layer_points(m:int,n:int,layer:int,)->list[tuple[int,int]]:points:list[tuple[int,int]]=[]forrowinrange(layer,m-layer-1):points.append((row,layer))forcolinrange(layer,n-layer-1):points.append((m-layer-1,col))forrowinrange(m-layer-1,layer,-1):points.append((row,n-layer-1))forcolinrange(n-layer-1,layer,-1):points.append((layer,col))returnpointsdefmatrixRotation(matrix:list[list[int]],r:int):# Write your code herem=len(matrix)n=len(matrix[0])output=[line.copy()forlineinmatrix]forlayerinrange(min(m,n)//2):dst=get_layer_points(m,n,layer)steps=r%len(dst)src=dst[-steps:]+dst[:-steps]foriinrange(len(dst)):output[dst[i][0]][dst[i][1]]=matrix[src[i][0]][src[i][1]]forlineinoutput:print(*line,sep=" ")
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 →
My Python3 solution. The rationale is that for each onion layer: 1. Get a list of coordinates on this layer (
dst
) 2. Rotate this list of coordinates to make a new list (src
) 3. For each coordinate indst
, set the value of this coordinate in the output matrix to the value of the correspondingsrc
coordinate in the original matrix