矩阵旋转90度

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
	   }
	   }
	}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值