An example of Java implementing a 90 degree clockwise rotation of a matrix

  • 2021-06-28 12:28:31
  • OfStack

It is easier to transpose the matrix by simply interchanging the vertical and horizontal subscripts.Rotating the matrix is a little cumbersome.

Solving ideas:

If the matrix is converted to 90 degrees, the vertical subscript of the original matrix is converted to the horizontal subscript of the new matrix.The horizontal subscript of the original matrix is converted to the vertical subscript of the new matrix in the opposite order.


public class Rotation {
 public static int[][] change(int [][]matrix){
 int [][]temp=new int[matrix[0].length][matrix.length];
 int dst=matrix.length-1;
 for(int i=0;i<matrix.length;i++,dst--){
 for(int j=0;j<matrix[0].length;j++){
 temp[j][dst]=matrix[i][j];
 }
 }
 return temp;
 }
 
 public static void main(String[]args){
 int [][]matrix={{1,2,3,4},{5,6,7,8},{9,10,11,12}};
 int [][]temp=change(matrix);
 for(int i=0;i<temp.length;i++){
 for(int j=0;j<temp[0].length;j++){
 System.out.print(temp[i][j]+"\t");
 }
 System.out.println();
 }
 }
 
}

The results are as follows:


9 5 1 
10 6 2 
11 7 3 
12 8 4 

It's not really complicated, but I didn't write it at the prescribed time.It still needs more practice.


Related articles: