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?
这里,我自己的假设是逆时针旋转90度。觉得有三种解法
解法一: 先倒置矩阵,再对称的交换列
解法二:寻找规律,其实就是将a[i][j]放到了a[j][N-1-i]位置
解法三:将矩阵拨开一圈一圈看,从外圈开始,旋转90度,然后内圈同样
演示如下:
代码如下:里边的代码在两个数交换上使用了两种不同的方法,也当时练习
import java.util.Scanner;
public class RotateMax
{
public static void main(String[] args)
{
final int N=4;
Scanner in = new Scanner(System.in);
//int[][] a={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
int[][] a=new int[N][N];
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
a[i][j]=in.nextInt();
}
}
show(rotate2(a,N),N);
show(rotate(a,N),N);
}
public static void show(int a[][],int n)
{
System.out.println();
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
public static void rotate(int a[][],int n)
{
int temp,i,j,m;
//矩阵倒置
for(i=0;i<n;i++)
{
for(j=i;j<n;j++)
{ //交换
temp=a[i][j];
a[i][j]=a[j][i];
a[j][i]=temp;
}
}
//对称交换列
for(i=0,j=n-1;i<j;i++,j--)
{
for(m=0;m<n;m++)
{
a[m][i]=a[m][i]^a[m][j];
a[m][j]=a[m][j]^a[m][i];
a[m][i]=a[m][i]^a[m][j];
}
}
}
public static int[][] rotate2(int[][] a,int n)
{
int i,j;
int[][] an=new int[n][n];
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
an[j][n-1-i]=a[i][j];
}
}
return an;
}
}
另外,没有详细看官方的解法, 一瞄过去没懂,但是一运行居然是转了个180度。。
public static void rotate3(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
}
}
}