原文:
Given an image represented by an NxN matrix, where each pixel in theimage is 4 bytes, write a method to rotate the image by 90 degrees.Can you do this in place?
译文:
一张图像表示成NxN的矩阵,图像中每个像素是4个字节,写一个函数把图像旋转90度。你能原地进行操作吗?(即不开辟额外的存储空间)
解答:每个pixel占用4bytes,也就是一个int。
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35
36 37 38 39 40 41 42
43 44 45 46 47 48 49
43 36 29 22 15 8 1
44 37 30 23 16 9 2
45 38 31 24 17 10 3
46 39 32 25 18 11 4
47 40 33 26 19 12 5
48 41 34 27 20 13 6
49 42 35 28 21 14 7
package com.zhuyu_deng.test;
public class Test
{
public static void main(String args[])
{
final int N = 7;
int arr[][] = new int[N][N];
int cnt = 1;
for (int i = 0; i < N; ++i)
{
for (int j = 0; j < N; ++j)
{
arr[i][j] = cnt++;
}
}
for (int i = 0; i < arr.length; ++i)
{
for (int j = 0; j < arr[i].length; ++j)
{
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
System.out.println();
rotateRight(arr, N);
for (int i = 0; i < arr.length; ++i)
{
for (int j = 0; j < arr[i].length; ++j)
{
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
private static void rotateRight(int[][] arr, int N)
{
for (int i = 0; i < N; ++i)
{
if (i < N - i - 1)
rotate(arr, i, N - i - 1);
}
}
private static void rotate(int[][] a, int x, int y)
{
for (int i = x, k = 0; i < y; ++i, k += 1)
{
int tmp1 = a[i][y];
a[i][y] = a[x][i];
int tmp2 = a[y][y - k];
a[y][y - k] = tmp1;
tmp1 = a[y - k][x];
a[y - k][x] = tmp2;
a[x][i] = tmp1;
}
}
}
与打印旋转矩阵有异曲同工之妙。