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.
defmatrixRotation(matrix,r):# Write your code herehDim=len(matrix[0])vDim=len(matrix)nbLayers=min(vDim/2,hDim/2)forlayerNbinrange(int(nbLayers)):innerVDim=vDim-layerNb*2innerHDim=hDim-layerNb*2# massive speed increase! why moving everything to end at the same point?fullRotationMoves=innerVDim*2+innerHDim*2-4rotationsToDo=r%fullRotationMovesforrrinrange(rotationsToDo):bottomLeftHold=matrix[-1-layerNb][layerNb]+0#bottomlefttopRightHold=matrix[layerNb][-1-layerNb]+0#topright# move down on the leftforiDinreversed(range(layerNb,layerNb+innerVDim)):ifiD>0:matrix[iD][layerNb]=matrix[iD-1][layerNb]+0# move up on the rightforiUinrange(layerNb,layerNb+innerVDim-1):ifiU<layerNb+innerVDim:matrix[iU][hDim-1-layerNb]=matrix[iU+1][hDim-1-layerNb]+0# move bottom to rightifinnerHDim>2:#onlyifthehorizontaldimensionis>2foriRinreversed(range(layerNb+1,layerNb+innerHDim)):matrix[-1-layerNb][iR]=matrix[-1-layerNb][iR-1]+0# move top to leftifinnerHDim>2:#onlyifthehorizontaldimensionis>2foriLinrange(layerNb,layerNb+innerHDim-1):matrix[layerNb][iL]=matrix[layerNb][iL+1]+0# apply bottomLeftHoldmatrix[-1-layerNb][layerNb+1]=bottomLeftHold+0# apply topRightHoldmatrix[layerNb][layerNb+innerHDim-2]=topRightHold+0foriinrange(m):print(' '.join(map(str,matrix[i])))returnmatrix
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 →
speed boost! avoid unnecessary rotations