Easy Understand Java Solution


  • 0
    Y

    Just loop from outer layer to inner layer

    public class Solution {
        public void rotate(int[][] matrix) {
            int len = matrix.length;
            int layer = (len - 1) / 2;
            int l = 0;
            while(l <= layer){
                for(int i=l + 1; i<len; i++){
                    swap(matrix, l, i, i, len - 1);
                }
                for(int i=l + 1; i<len; i++){
                    swap(matrix, l, i, len - 1, len - i - 1 + l);
                }
                for(int i=l + 1; i<len; i++){
                    swap(matrix, l, i, len - i - 1 + l, l);
                }
                
                l += 1;
                len -= 1;
            }
        }
        
        public void swap(int[][] matrix, int x1, int y1, int x2, int y2){
            int temp = matrix[x1][y1];
            matrix[x1][y1] = matrix[x2][y2];
            matrix[x2][y2] = temp;
        }
    }
    

Log in to reply
 

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