Rotate the matrix directly, Java in place solution


  • 0
    Y
    public void rotate(int[][] matrix) {
        int start = 0, end = matrix.length-1;
        while(start<end){
            for(int i=start;i<end;i++){
                swap(matrix,start,i,i,end,end,end+start-i,end+start-i,start);
            }
            start++;
            end--;
        }
    }
    private void swap(int[][] matrix,int r1,int c1,int r2,int c2,int r3,int c3,int r4,int c4){
        int temp = matrix[r1][c1];
        matrix[r1][c1] = matrix[r4][c4];
        matrix[r4][c4] = matrix[r3][c3];
        matrix[r3][c3] = matrix[r2][c2];
        matrix[r2][c2] = temp;
    }

Log in to reply
 

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