Solution: Rotate Image
Let's solve the Rotate Image problem using the Matrices pattern.
We'll cover the following
Statement#
Given an matrix, rotate the matrix 90 degrees clockwise. The performed rotation should be in place, i.e., the given matrix is modified directly without allocating another matrix.
Note: The function should only return the modified input matrix.
Constraints:
matrix.lengthmatrix[i].length-
matrix.length -
matrix[i][j]
Solution#
The idea is to make groups of four cells and rotate them by 90 degrees clockwise.
Here’s how the algorithm works:
-
We run a loop where
rowranges from0ton / 2.-
Within this loop, we run a nested loop where
colranges fromrowton - row - 1. These loops traverse the groups of four cells in the matrix. In this nested loop, we perform three swaps:-
The value of the top-left cell is swapped with the value of the top-right cell.
-
The value of the top-left cell is swapped with the value of the bottom-right cell.
-
The value of the top-left cell is swapped with the value of the bottom-left cell.
-
-
The current group of four cells has been rotated by degrees. We now move to the next iteration of the outer loop to rotate the next group.
-
-
We repeat the process above until the whole matrix has been rotated.
Let’s look at the following illustration to get a better understanding of the solution:
1 of 26
2 of 26
3 of 26
4 of 26
5 of 26
6 of 26
7 of 26
8 of 26
9 of 26
10 of 26
11 of 26
12 of 26
13 of 26
14 of 26
15 of 26
16 of 26
17 of 26
18 of 26
19 of 26
20 of 26
21 of 26
22 of 26
23 of 26
24 of 26
25 of 26
26 of 26
Let’s have a look at the code for the algorithm we just discussed:
Rotate Image
Spiral Matrix