Matrix Rotation

Darrick Pang
3 min readFeb 26, 2021

Last week, I discussed the problem of rotating an array. To refresh the problem, the question is given an array

var arr = [1, 2, 3, 4, 5]

and number of rotations

var k = 2

the final rotation should be

[4, 5, 1, 2, 3]. 

To do this, we splice the array by removing the last number(s) and add them to a new array. Then we proceed to add the new array back to the spliced array. More details will be in the reference.

Now, let’s try to solve the matrix rotation problem. Given a matrix

var matrix = [[1,2,3],
[4,5,6],
[7,8,9]],

rotate this 90 degrees clockwise such that the final matrix is

Output: [[7,4,1],
[8,5,2],
[9,6,3]].

The first thing we want to do is remember that each element in the matrix is an array. Then we want to get the first and subsequent element of each array in the matrix and return

[[1, 4, 7],
[2, 5, 8],
[3, 6, 9]].

Step one is to grab each element in each array with the matrix. The code is

matrix.map(row => row[index]). 

The “index” is each element in the array, from 0 to the array length minus 1. For example, if we let index = 0, we get

[1, 4, 7],

which is the first element of each row. Next step is we want to iterate each element in the matrix

const flip = matrix => (
matrix.map((column, i) => (
matrix.map(row => row[i])
))
).

What this code is doing is that first, it iterates through each array element and grabs ith element of each array and inserts it into a new one. Then it repeats until it iterates through the entire matrix. If we just look at the flip function, the array will be

[[1, 4, 7],
[2, 5, 8],
[3, 6, 9]] .

Another way to write the flip function using for loops is

function flip(matrix){
var newMatrix = []
for(var x = 0; x < matrix.length; x++){
var arr = []
for(var y = 0; y < matrix.length; y++){
arr.push(matrix[y][x])
}
newMatrix.push(arr)
}
return newMatrix
}

The reason why x and y are flipped is that it will give us the above answer.

We are done with the flip function. We can see the flip output array is just the reverse of the rotated matrix. So all we need to do is reverse each array in the matrix

function rotate(matrix){
let arr = flip(matrix)
let rotated = []
for(var x = 0; x < arr.length; x++){
rotated.push(arr[x].reverse())
}
return rotated
}.

Let’s look at

[[1,2,3],
[4,5,6],
[7,8,9]].

The expected output is

Output: [[7,4,1],
[8,5,2],
[9,6,3]],

and the answer is indeed a match from figure 1.

Fig. 1: Answer matches the expected output.

Let’s look at another. Given a matrix

[[5,1,9,11],
[2,4,8,10],
[13,3,6,7],
[15,14,12,16]],

the expected output is

[[15,13,2,5],
[14,3,4,1],
[12,6,8,9],
[16,7,10,11]],

and we see from figure 2, it is indeed a match.

Fig. 2: Answer for the second array.

We can see the algorithm works.

References

  1. https://leetcode.com/problems/rotate-image/
  2. https://darrickpang90.medium.com/rotate-an-array-690fbcb17f6e

--

--