Given an n × n 2D matrix representing an image.
Rotate the image 90 degrees clockwise. An example is as follows:
Given matrix = [ [ 5, 1, 9,11], [ 2, 4, 8,10], [13, 3, 6, 7], [15,14,12,16] ], Rotate the input matrix in place so that it becomes: [ [15,13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7,10,11] ]
For the element matrix[i][j] in the matrix, after rotating it by 90 degrees, the corresponding position is matrix[j][Mi], and M is n-1
For example, the value of matrix[0][0] is 5, and the value of matrix[0][3-0] after rotation is 5
The value of matrix[1][0] is 2, and the value of matrix[0][3-1] after rotation is 2
Implementation:
Rotate the outermost circle of the matrix first, then gradually rotate the inner circle.
as matrix
5 |
1 |
9 |
11 |
2 |
4 |
8 |
10 |
13 |
3 |
6 |
7 |
15 |
14 |
12 |
16 |
Rotate the outermost circle first, then the inner circle.
The outermost circle only needs to rotate 5, 1, and 9, and the innermost circle only needs to rotate 4.
5->11 11->16 16->15 15->5, rotate 1, 9 in the same way
for an nxn matrix
The first circle needs to rotate n-1 elements, matrix[0][0] - matrix[0][n-2]
The second circle needs to rotate n-3 elements, matrix[1][1] - matrix[1][n-3]
3rd lap n-5
。。。
As shown below:
code show as below:
public static void rotate(int[][] matrix) { int M = matrix.length - 1 ; // Number of elements to be rotated in each row int len = M; int temp; int i=0, j=0 ; while (len > 0 ) { for (j=i; j<i+len; j++ ) { // rotate four elements temp = matrix[j][M- i]; matrix[j][M-i] = matrix[i][j]; matrix[i][j] = matrix[M-j][i]; matrix[M-j][i] = matrix[M-i][M-j]; matrix[M-i][M-j] = temp; } i++; len - = 2 ; } }