码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 48 Rotate Image

时间:2016-04-12 00:03:53      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:

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?

思路:把矩阵看成是由多个正方形一层一层包围起来的。转动的时候就是转动正方形的边,只要把边上的每个数依次替换就好,四个方向也就是进行四次替换,依次对每一层进行替换。

总层数 = matrix.length/2,第i层从第matrix[i][i]开始到matrix[i][n-1-1-i]结束,注意保存temp = matrix[i][i],确保最后一次替换值不被覆盖,每一轮四个方向进行四次替换

public class S048 {
    public void rotate(int[][] matrix) {
        //找规律,把矩阵每一层四个方向上的每个数依次替换
        if (matrix.length == 1)
            return ;
        int len = matrix.length;
        for (int i = 0;i<len/2;i++) {
            for (int j = i;j<len-1-i;j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[len-1-j][i];
                matrix[len-1-j][i] = matrix[len-1-i][len-1-j];
                matrix[len-1-i][len-1-j] = matrix[j][len-1-i];
                matrix[j][len-1-i] = temp;
            }
        }
    }
    public static void main(String[] args) {
        S048 s = new S048();
        int [][] nums= {{1,2,3,4},{1,2,3,4},{1,2,3,4},{1,2,3,4}};
        s.rotate(nums);
    }
}

 

Leetcode 48 Rotate Image

标签:

原文地址:http://www.cnblogs.com/fisherinbox/p/5380678.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!