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.
publicstaticvoidmatrixRotation(List<List<int>>matrix,intr){varcol=matrix.First().Count;varrow=matrix.Count;varlayers=Math.Min(col,row)/2;varlayerLines=newList<List<int>>();// Iterate through layers to get them as a list of numbers.for(intlayer=0;layer<layers;layer++){varline=newList<int>();// get left values of the layerfor(inti=layer;i<row-1-layer;i++){line.Add(matrix[i][layer]);}// get bottom values of the layerfor(inti=layer;i<col-1-layer;i++){line.Add(matrix[row-1-layer][i]);}// get right values of the layerfor(inti=row-1-layer;i>layer;i--){line.Add(matrix[i][col-1-layer]);}// get top values of the layerfor(inti=col-1-layer;i>layer;i--){line.Add(matrix[layer][i]);}layerLines.Add(line);}// Iterate through lines and rotate anti-clockwiseforeach(varlineinlayerLines){// Once rotated by line count result will be the same// By using % we can optimize and get the real count.varrotations=r%line.Count;for(inti=0;i<rotations;i++){varlast=line.Last();line.RemoveAt(line.Count-1);line.Insert(0,last);}}// Replace the lines in layers.for(intlayer=0;layer<layers;layer++){varline=layerLines[layer];varindex=0;// left layer valuesfor(inti=layer;i<row-1-layer;i++){matrix[i][layer]=line[index++];}// bottom layer valuesfor(inti=layer;i<col-1-layer;i++){matrix[row-1-layer][i]=line[index++];}// right layer valuesfor(inti=row-1-layer;i>layer;i--){matrix[i][col-1-layer]=line[index++];}// top layer valuesfor(inti=col-1-layer;i>layer;i--){matrix[layer][i]=line[index++];}layerLines.Add(line);}// Print outputfor(inti=0;i<row;i++){for(intj=0;j<col;j++){Console.Write(matrix[i][j]+" ");}Console.WriteLine();}}
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 →
C#