Given an n × n represents a two-dimensional matrix image.
The image is rotated 90 degrees clockwise.
Description:
You have to rotate the image in place, which means you need to directly modify the two-dimensional matrix input. Do not use another matrix to rotate an image.
Example 1:
Given = Matrix
[
[l, 2,3],
[4,5,6],
[7,8,9]
],
In situ rotation of the input matrix, so that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 2:
Given = Matrix
[
[. 5,. 1, 9,11],
[2,. 4, 8,10],
[13 is,. 3,. 6,. 7],
[15,14,12,16]
],
In situ rotation of the input matrix, so that it becomes:
[
[15, 13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7, 10 ]
]
answer:
public void rotate(int[][] matrix) { transpose(matrix); reverse(matrix); } public static void transpose(int[][] matrix){ int length=matrix.length; for(int i=0;i<length;i++){ for(int j=i;j<length;j++){ int tmp=matrix[j][i]; matrix[j][i]=matrix[i][j]; matrix[i][j]=tmp; } } } public static void reverse(int[][] matrix){ int length=matrix.length; for(int i=0;i<length;i++){ for(int j=0;j<length/2;j++){ int tmp=matrix[i][j]; matrix[i][j]=matrix[i][length-1-j]; matrix[i][length-1-j]=tmp; } } }
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/rotate-image