Tuesday, February 11, 2014

Rotate Image

You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?

Solution:
Need to be careful.

public class Solution {
    public void rotate(int[][] matrix) {
        int n = matrix.length;
        for(int layer = 0; layer < n/2; layer++){
        
            int temp = 0;
            for(int i=layer; i<=n-2-layer; i++){
                //matrix[layer][i];  // top
                //matrix[i][n-1-layer]; // right
                //matrix[n-1-layer][n-1-i]; // bottom
                //matrix[n-1-i][layer]; //left
            
                // temp = top
                temp = matrix[layer][i];
                // top = left
                matrix[layer][i] = matrix[n-1-i][layer]; 
                // left = bottom
                matrix[n-1-i][layer] = matrix[n-1-layer][n-1-i];
                // bottom = right
                matrix[n-1-layer][n-1-i] = matrix[i][n-1-layer];
                // right = temp
                matrix[i][n-1-layer] = temp;
            }
            
        }
    }
}

No comments:

Post a Comment