Question
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
Stats
Frequency | 2 |
Difficulty | 4 |
Adjusted Difficulty | 2 |
Time to use | -------- |
Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)
Solution
This question is easy, just swap numbers in place.
My code
public class Solution {
public void rotate(int[][] matrix) {
if (matrix == null) {
return;
}
int N = matrix.length;
// 5 - 2/3
// 6 - 3/3
int m = N / 2;
int n = (N + 1) / 2;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
// eg. N = 4, i = 0, j = 1
// (0, 1) <- (2, 0)
// (2, 0) <- (3, 2)
// (3, 2) <- (1, 3)
// (1, 3) <- (0, 1)
int temp = matrix[i][j];
matrix[i][j] = matrix[N - 1 - j][i];
matrix[N - 1 - j][i] = matrix[N - 1 - i][N - 1 - j];
matrix[N - 1 - i][N - 1 - j] = matrix[j][N - 1 - i];
matrix[j][N - 1 - i] = temp;
}
}
}
}
A cleaner version from this blog.
This code is very concise and beautiful, because it added the following 2 variables:
x = n-1-a
y = n-1-b
public void rotate(int[][] matrix) {
for (int a = 0, x = matrix.length - 1; a < x; a++, x--) {
for (int b = a, y = x; b < x; b++, y--) {
int t = matrix[a][b];
matrix[a][b] = matrix[y][a];
matrix[y][a] = matrix[x][y];
matrix[x][y] = matrix[b][x];
matrix[b][x] = t;
}
}
}