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

Cracking the Coding Interview Q1.6

时间:2014-07-08 22:06:25      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   for   div   res   

Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?

 

思路:从最晚层向内,一层一层交换。

 

    public static void rotate(int[][] matrix, int n) {
        for (int layer = 0; layer < n / 2; ++layer) {
            int first = layer;
            int last = n - 1 - layer;
            for(int i = first; i < last; ++i) {
                int offset = i - first;
                int top = matrix[first][i]; // save top

                // left -> top
                matrix[first][i] = matrix[last-offset][first];             

                // bottom -> left
                matrix[last-offset][first] = matrix[last][last - offset]; 

                // right -> bottom
                matrix[last][last - offset] = matrix[i][last]; 

                // top -> right
                matrix[i][last] = top; // right <- saved top
            }
        }
    }

 

Cracking the Coding Interview Q1.6,布布扣,bubuko.com

Cracking the Coding Interview Q1.6

标签:style   blog   color   for   div   res   

原文地址:http://www.cnblogs.com/jdflyfly/p/3830580.html

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