LeetCode: How to rotate an image clockwise

Problem

You are given an nn x nn 2D matrix representing an image, and you need to rotate the image clockwise by 90 degrees. You have to rotate the image in place, i.e., you have to modify the input 2D matrix directly. Do not allocate another 2D matrix and perform the rotation.

Algorithm

  1. Switch the rows up and down. Let’s say we have nn rows: switch the 1st1^{st} row and the nthn^{th} row, the 2nd2^{nd} row and the (n1)th(n-1)^{th} row, and so on.
  2. Apply transpose on the resultant matrix.

The transpose of a matrix is obtained by changing its rows into columns and its columns into rows.

The given matrix
1 of 19

Code

class Solution {
public void rotate(int[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return;
int rows = matrix.length;
int cols = matrix[0].length;
for(int first=0,last=rows-1; first<last; first++, last--){
int[] tmp = matrix[first];
matrix[first] = matrix[last];
matrix[last] = tmp;
}
for(int i=0;i<rows;i++){
for(int j=i+1;j<cols;j++){
int tmp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = tmp;
}
}
}
}

Free Resources