Java in-place (no extra space) solution using swap


  • 0
    P

    If you want to swap 4 corners clockwise without using extra space, it takes 3 swaps to rotate them. In each side, you do this operation square size - 1 times. And you repeat this entire process over outer rectangle to inner rectangle.

    public class Solution {
        public void rotate(int[][] matrix) {
            for(int i = 0; i < matrix.length/2; i++) {
                
                for(int j = 0; j <  matrix.length-(2*i)-1; j++) {
    
                    swap(matrix, i, i+j, matrix.length-1-i-j, i);
                    swap(matrix, matrix.length-1-i-j, i, matrix.length-1-i, matrix.length-1-i-j);
                    swap(matrix, matrix.length-1-i, matrix.length-1-i-j, i+j, matrix.length-1-i);
    
                }
            }
        }
        
        private void swap(int[][] matrix, int a1, int b1, int a2, int b2) {
            int temp = matrix[a1][b1];
            matrix[a1][b1] = matrix[a2][b2];
            matrix[a2][b2] = temp;
    
        }
    
    }

Log in to reply
 

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