How to Rotate matrix (angle%90===0) in place?

Helloo, still on another personal coding exercise.

Matrix manipulation

and recursion: two areas I’m trying to understand. this is about matrix(Rotation) any angle but this is for +90. Is there a way to adjust my code so that I manipulate the matrix in place and not use a copy?

function rotateMatrix90(m) {

    f = new Array(m.length).fill().map(()=>[])

    h = m.length

  for (i = 0; i < m.length ; i++) {

      for (k = 0; k < m[i].length; k++) {

          f[k][i] = m[h-1-i][k];


  return f


const answer = rotateMatrix90([

  ['A', 'B', 'C', 'D'],

  ['E', 'F', 'G', 'H'],

  ['I', 'J', 'K', 'L'],

  ['M', 'N', 'O', 'P'],



  ["M", "I", "E", "A"],

  ["N", "J", "F", "B"], 90 clockwise

  ["O", "K", "G", "C"],

  ["P", "L", "H", "D"],


Thank you

Have you tried goggling for the answer? I have a feeling if you searched for “rotate matrix in place” you will find what you are looking for :slight_smile:

Thanks, but, I just wanted to use the code above and not just some boiler plate code from out there, ie something I can wrap my head around.

You simply exchange row/number digits. This problem becomes simply a problem of switching two numbers and nesting two loops in the right way.

Recursion here would be confusing to me.

arr[0][3] becomes rotatedArrarr[3][0]
arr[3][0] becomes rotatedArrarr[0][3]

You need to do this for ~half of the original array. One switch operation takes care of two numbers. Nested loops that start at [0][0], [1][1] ... [n][n] (for simplicity’s sake, I know it should be [n][n+1], but is more complicated and gain is too small).

I wasn’t suggesting you just blindly copy some code you find on the internets. You can find explanations for how to do this and then once you understand how to do it you can apply it to your own code. Much faster than having to wait for someone here to take the time to type you up an explanation :slight_smile:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.