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.
I was able to do exactly this in my case. I did it by computing the amount of rotations needed for each layers, and swapping each elements accordingly until I reach the end of my number of rotation required. an extra check I had to do was to reinitialize my starting position if we reached our initial position for one of our swap i.e. (0,0) for the first layer.
Here's my code, kinda crappy but it passes all tests:
importjava.io.*;importjava.util.*;importjava.text.*;importjava.math.*;importjava.util.regex.*;publicclassSolution{staticvoidmatrixRotation(int[][]matrix,intm,intn,intr){intlayers=Math.min(m,n)/2;for(intl=0;l<layers;l++){intm_l=l+m-2*l;intn_l=l+n-2*l;intnbRotationsNeeded=(m_l-1-l)*2+(n_l-1-l)*2;intboundedR=r%nbRotationsNeeded;if(boundedR==0)continue;introtationCount=0;inti=l;intj=l;intcurrent_first_i=i;intcurrent_first_j=j;intcurrent=matrix[i][j];while(rotationCount<nbRotationsNeeded){intcurrentRotation=boundedR;while(currentRotation!=0){// go downif(j==l&&i<m_l-1){i++;}// go rightelseif(i==m_l-1&&j<n_l-1){j++;}// go upelseif(j==n_l-1&&i>l){i--;}// go leftelseif(i==l&&j>l){j--;}currentRotation--;}inttemp=matrix[i][j];matrix[i][j]=current;if(current_first_i==i&¤t_first_j==j){// go downif(j==l&&i<m_l-1){i++;}// go rightelseif(i==m_l-1&&j<n_l-1){j++;}// go upelseif(j==n_l-1&&i>l){i--;}// go leftelseif(i==l&&j>l){j--;}current_first_i=i;current_first_j=j;temp=matrix[i][j];}current=temp;rotationCount++;}}// printfor(inti=0;i<m;i++){for(intj=0;j<n;j++){System.out.print(matrix[i][j]+" ");}System.out.println();}}publicstaticvoidmain(String[]args){Scannerin=newScanner(System.in);intm=in.nextInt();intn=in.nextInt();intr=in.nextInt();int[][]matrix=newint[m][n];for(intmatrix_i=0;matrix_i<m;matrix_i++){for(intmatrix_j=0;matrix_j<n;matrix_j++){matrix[matrix_i][matrix_j]=in.nextInt();}}matrixRotation(matrix,m,n,r);in.close();}}
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 →
I was able to do exactly this in my case. I did it by computing the amount of rotations needed for each layers, and swapping each elements accordingly until I reach the end of my number of rotation required. an extra check I had to do was to reinitialize my starting position if we reached our initial position for one of our swap i.e. (0,0) for the first layer.
Here's my code, kinda crappy but it passes all tests: