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

思路:先将矩阵转置,然后将第一列与最后一列替换,第二列与倒数第二列替换。。一次类推。。即可得到

public class Solution {
    public void rotate(int[][] matrix) {
        int n = matrix.length;
        
        for(int i=1;i<n;i++){
            for(int j=0;j<i;j++){
                int temp = matrix[i][j];
                matrix[i][j]=matrix[j][i];
                matrix[j][i]=temp;
            }
        }
        
        for(int m=0;m<n/2;m++){
            for(int mm=0;mm<n;mm++){
                int temp = matrix[mm][m];
                matrix[mm][m]=matrix[mm][n-m-1];
                matrix[mm][n-m-1]=temp;
            }
        }
        
    }
}

 

 

posted @ 2014-05-11 18:57  一弦一仙  阅读(126)  评论(0编辑  收藏  举报