原文:
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?
译文:
一张图像表示成NxN的矩阵,图像中每个像素是4个字节,写一个函数把图像旋转90度。 你能原地进行操作吗?(即不开辟额外的存储空间)
关键是in place旋转,不能另开空间
两种做法:
1 通用做法如下图:用swap的方法,把黄->绿,绿->蓝,蓝->红,红->黄
又注意到黄的部分:总是在first行,只是列在变,所以可以表示成 M[first][i]
绿的部分:总在last列,只是行在变,所以M[i][last]
蓝的部分:总在last行,只是列在变,所以M[last][last-offset]
红的部分:总在first列,只是行在变,所以M[last-offset][first]
offset是表示当前元素i到first元素的距离,用来和last搭配使用
first i last
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
2 一种捷径如果是逆时针旋转则可以第一步交换主对角线两侧的对称元素,第二步交换第i行和第n-1-i行,即得到结果。
顺时针同理。具体参考: http://hawstein.com/posts/1.6.html 但我觉得不如第一种有普遍性。
Followup:
这道题关键是矩阵是一个方形矩阵,所以能in place旋转。但如果是一个M*N的矩阵,则该怎么做?
可参考LeetCode上有一道题:Spiral Matrix I II
package Arrays_Strings; import CtCILibrary.AssortedMethods; public class S1_6 { // 顺时针90度旋转矩阵 public static void rotateClockwise(int[][] M, 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; // offset: 当前处理元素和第一个元素之间之差,用于last元素向前 int top = M[first][i]; // Save top M[first][i] = M[last-offset][first]; // left -> top M[last-offset][first] = M[last][last-offset]; // bottom -> left M[last][last-offset] = M[i][last]; // right -> bottom M[i][last] = top; // top->right } } } // 逆时针90度旋转矩阵 public static void rotateAntiClockwise(int[][] M, 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 = M[first][i]; // Save top M[first][i] = M[i][last]; // right -> top M[i][last] = M[last][last-offset]; // bottom -> right M[last][last-offset] = M[last-offset][first]; // left -> bottom M[last-offset][first] = top; // top->left } } } public static void main(String[] args) { int[][] matrix = AssortedMethods.randomMatrix(5, 5, 0, 9); AssortedMethods.printMatrix(matrix); rotateClockwise(matrix, 5); System.out.println(); AssortedMethods.printMatrix(matrix); rotateAntiClockwise(matrix, 5); System.out.println(); AssortedMethods.printMatrix(matrix); } }
Arrays_Strings 90度顺时针逆时针旋转方形矩阵 @CareerCup,布布扣,bubuko.com
Arrays_Strings 90度顺时针逆时针旋转方形矩阵 @CareerCup
原文:http://blog.csdn.net/fightforyourdream/article/details/20108431