Rotate Image
1 min readMay 15, 2019
Question: You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
You may view the full question here.
Approach 1: The discussion forum had some brilliant ideas. One approach is —
- Reverse the rows of the matrix — top-down manner
- Swap the elements of the matrix diagonally, with the diagonal starting from the top left corner to the bottom right corner of the matrix
Here’s the code —
//Approach 1:
//Runtime: 0ms
//Memory usage: 35.5MBclass Solution {
public void rotate(int[][] matrix) {
int len = matrix.length;
//Reverse
for(int r = 0; r<len/2; r++){
for(int c = 0; c<matrix[0].length; c++){
int temp = matrix[r][c];
matrix[r][c] = matrix[len-r-1][c];
matrix[len-r-1][c] = temp;
}
}
//Swap
for(int r = 0; r<len; r++){
for(int c = r+1; c<matrix[0].length; c++){
int temp = matrix[r][c];
matrix[r][c] = matrix[c][r];
matrix[c][r] = temp;
}
}
}
}
Find more posts here.
Cheers & Chao!