In place solution with one swap subroutine


  • 0
    5
     public void swap(int[][] matrix, int i, int j){// rotate one point clockwise
            int n=matrix.length;
            int temp = matrix[j][n-1-i];
            matrix[j][n-1-i] = 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] = temp;
        }
        
        public void rotate(int[][] matrix) {
            int n=matrix.length;
            int x=n%2==0?n/2:n/2+1, y=n/2; // determine the window size of the points
            for(int i=0;i<x;i++){
                for(int j=0;j<y;j++){
                    swap(matrix,i,j);
                }
            }
        }

Log in to reply
 

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