Java, Rotate layer by layer, inside out, O(1) space,


  • 0
    C

    For image of odd edge length, there will be a center pixel and layers of "hollow" rectangles around it. For each layer, we iterate through one edge and for each pixel we visit, we find out the "rotation 4 pixel group" and use a temporary variable to swap them. For even length the idea is similar, except that we have to change the coordinate system.

    class Solution {

    public void rotate(int[][] matrix) {
        if (matrix.length % 2 == 1) {
            int n = matrix.length;
            int m = ( n - 1 ) / 2;            
            for (int layer = 1; layer <= m; layer ++) {               
                for (int i = 0; i < 2 * layer; i++) {
    
                    int tmp = matrix[m - layer][m - layer + i];
                    matrix[m - layer][m - layer + i] = matrix[m + layer - i][m - layer];                 
                    matrix[m + layer - i][m - layer] = matrix[m + layer][m + layer - i];
                    matrix[m + layer][m + layer - i] = matrix[m - layer + i][m + layer];
                    matrix[m - layer + i][m + layer] = tmp;
    
                }
            }           
        }
        if (matrix.length % 2 == 0) {
            int n = matrix.length;
            int m = n / 2 - 1;
            for (int layer = 0; layer <= m; layer ++) {
                for ( int i = 0; i < 2 * layer + 1; i++ ) {
                    int tmp = matrix[m - layer][m - layer + i];
                    matrix[m - layer][m - layer + i] = matrix[m + layer + 1 - i][m - layer];             
                    matrix[m + layer + 1 - i][m - layer] = matrix[m + layer + 1][m + layer + 1 - i];
                    matrix[m + layer + 1][m + layer + 1 - i] = matrix[m - layer + i][m + layer + 1];
                    matrix[m - layer + i][m + layer + 1] = tmp;
                }
            }
        }        
    }
    

    }


Log in to reply
 

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