48. Rotate Image

48. 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?

 
Hide Tags
 Array
 
public class Solution {
    public void rotate(int[][] matrix) {
        //rotate layer by layer.
        int n = matrix.length;
        if(n<=1)
            return;
        
        for(int layer = 0; layer<n/2; ++layer){
            for(int col = layer; col < n-1-layer; ++col){
                int temp = matrix[layer][col];
                
                matrix[layer][col] = matrix[n-1-col][layer];
                matrix[n-1-col][layer] = matrix[n-1-layer][n-1-col];
                matrix[n-1-layer][n-1-col] = matrix[col][n-1-layer];
                matrix[col][n-1-layer] = temp;
            }
        }
    }
}

 

 
posted @ 2016-07-25 05:24  新一代的天皇巨星  阅读(173)  评论(0)    收藏  举报