Share my in-place java code with sample illustration


  • 0
    M
    /*
        rotate layer by layer.
        
        1   2   3   4
        5   6   7   8
        9   10  11  12
        13  14  15  16
        
        1-->4-->16-->13-->1
        2-->8-->15-->9-->2
        3-->12-->14-->5-->3
    */
    public class Solution {
        public void rotate(int[][] matrix) {
            if (matrix == null) { return; }
            int n = matrix.length;
            if (n == 1) { return; }
            int sRow = 0, sCol = 0;
            for (int i=n-1; i>0; i-=2, ++sRow, ++sCol) {
                for (int j=0; j<i; ++j) {  // i "groups" to rotate
                    int save = matrix[sRow][sCol+j];
                    matrix[sRow][sCol+j] = matrix[sRow+i-j][sCol];
                    matrix[sRow+i-j][sCol] = matrix[sRow+i][sCol+i-j];
                    matrix[sRow+i][sCol+i-j] = matrix[sRow+j][sCol+i];
                    matrix[sRow+j][sCol+i] = save;
                }
            }
        }
    }

Log in to reply
 

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