leetcode -- 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?

如下图,首先沿逆对角线翻转一次,然后按x轴中线翻转一次。

 1 public void rotate(int[][] matrix) {
 2         // Start typing your Java solution below
 3         // DO NOT write main() function
 4         int len = matrix.length;
 5         if(len == 0)
 6             return;
 7         
 8         for(int i = 0; i < len - 1; i++){
 9             for(int j = 0; j < len -i; j++){
10                 swap(matrix, i, j, len - 1 - j, len - 1 -i);
11             }
12         }
13         
14         
15         for(int i = 0; i < len / 2; i++){
16             for(int j = 0; j < len; j++){
17                 swap(matrix, i, j, len - 1 -i, j);
18             }
19         }
20     }
21     
22     public void swap(int[][] matrix, int i, int j, int m, int n){
23         int tmp = matrix[i][j];
24         matrix[i][j] = matrix[m][n];
25         matrix[m][n] = tmp;
26     }

 

posted @ 2013-08-07 13:27  feiling  阅读(231)  评论(0编辑  收藏  举报