Leetcode 48. Rotate Image (Medium) (java)
Tag: Array
Difficulty: Medium
/*
48. Rotate Image (Medium)
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?
*/
public class Solution {
public void rotate(int[][] matrix) {
if (matrix == null || matrix[0].length == 0) return;
int n = matrix.length - 1;
for (int i = 0; i < (n + 2) / 2; i++) {
for (int j = i; j < n - i; j++) {
swap(matrix, i, j, j, n - i);
swap(matrix, i, j, n - i, n -j);
swap(matrix, i, j, n - j, i);
}
}
}
private void swap(int[][] matrix, int i, int j, int k, int l) {
int temp = matrix[i][j];
matrix[i][j] = matrix[k][l];
matrix[k][l] = temp;
}
};