Easy to understand Java Solution


  • 0
    S

    Just remember this formula and you are all set:
    i' = j;
    j' = n-1-i;

    Code:

    rotate(int[][] matrix){
    //if null do nothing Obviously!!
    if(matrix==null || matrix.length==0) return;
    //store matrix dimension
    int n = matrix.length();
    int counter = n/2; //need to run the loop this many times
    for(int c =0; c<counter;c++){
         for(int i=c,j=c;j<n-1-c;j++){
              int temp = matrix[i][j];
              //Remember formula : i' = j , j' = n-1-i
              int i2 = j;
              int j2 = n-1-i;
              int i3 = j2;
              int j3 = n-1-i2;
              int i4 = j3;
              int j4 = n-1-i3;
              // Good to go!!
             matrix[i][j] = matrix[i4][j4];
             matrix[i4][j4] = matrix[i3][j3];
             matrix[i3][j3] = matrix[i2][j2];
             matrix[i2][j2] = temp; // matrix[i][j]
           }
       }
     
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.