Monday, July 6, 2015

Rotate Image

You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise).
Have you met this question in a real interview? 
Yes
Example
Given a matrix
[
    [1,2],
    [3,4]
]
rotate it by 90 degrees (clockwise), return
[
    [3,1],
    [4,2]
]

Challenge
Do it in-place.

public class Solution {
    /**
     * @param matrix: A list of lists of integers
     * @return: Void
     */
    public void rotate(int[][] matrix) {
        
        // write your code here
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
            return;
        }
        int n = matrix.length;
        
        for(int layer = 0; layer < n / 2; layer++){
            for(int i = layer; i < n - 1 - layer; i++){
                int temp = matrix[i][layer];
                matrix[i][layer] = matrix[n-1-layer][i];
                matrix[n-1-layer][i] = matrix[n -1 - i][n-layer-1];
                matrix[n-1-i][n-1-layer] = matrix[layer][n-1-i];
                matrix[layer][n-1-i] = temp;
            }
        }
    }
}

No comments:

Post a Comment