in-place solution, 2 round swaps.


  • 1

    Please prepare a piece of paper, make it square, make marks (1, 2, 3, 4) on the corners.

    1. flip, upside down
    2. flip along the main diagonal (top-left to right-bottom)
      then it's changed 90 degree clockwise
    public class Solution {
        public void rotate(int[][] matrix) {
            int rows = matrix.length;
            int cols = matrix[0].length;
            //upside down
            for(int i = 0; i < rows / 2; i++) {
                for(int j = 0; j < cols; j++) {
                    int r = rows - 1 - i;
                    swap(matrix, i, j, r, j);
                }
            }
            
            //main diag swap
            for(int i = 0; i < rows; i++){
                for(int j = 0; j < i; j++){
                    swap(matrix, i, j, j,i);
                }
            }
        }
        
        public void swap(int[][] matrix, int r1, int c1, int r2, int c2) {
            int temp = matrix[r1][c1];
            matrix[r1][c1] = 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.