Rotate Image

来源:互联网 发布:电脑图标全变成windows 编辑:程序博客网 时间:2024/05/21 17:11

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

public static void rotate(int[][] matrix) {int len=matrix.length;int[][] t=new int[len][len];for(int i=0;i<len;i++){for(int j=0;j<len;j++)t[j][len-1-i]=matrix[i][j];}matrix=t;}
The problem is that Java is pass by value not by refrence! "matrix" is just a reference

 to a 2-dimension array. If "matrix" is assigned to a new 2-dimension array in the method,

 the original array does not change. Therefore, there should be another loop to assign 

each element to the array referenced by "matrix".

public static void rotate(int[][] matrix) {int len=matrix.length;int[][] t=new int[len][len];for(int i=0;i<len;i++){for(int j=0;j<len;j++)t[j][len-1-i]=matrix[i][j];}for(int i=0;i<len;i++){for(int j=0;j<len;j++)matrix[i][j]=t[i][j];}}



0 0