Title Description
[Image] rotation
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 =
[
[1,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, 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,11]
]
Thinking
If the direct hard turn, is difficult to find regularity, you can convert it, first along a diagonal matrix to make a mirror inversion, and then do the effect can be achieved by reversing the rotational symmetry of a y-axis by 90 degrees.
The first step in exchange, can be done with a two cycle, but do not need to traverse all the note positions, can only traverse a half (the upper half of a diagonal line), then traverse to its mirror element position .
[1,2,3], [1,4,7]
[4,5,6], -> 沿着主对角线翻转 [2,5,8]
[7,8,9] [3,6,9]
The second step is also a double loop, the first step to do matrix after about exchange, i.e. the y-axis inversion symmetry, the same elements need only to traverse to the left
[1,4,7], [7,4,1]
[2,5,8], -> 沿着y轴(中间竖线)翻转 [8,5,2]
[3,6,9] [9,6,3]
Code
class Solution {
public void rotate(int[][] matrix) {
for(int i = 0; i < matrix.length; i++) {
for(int j = i; j <matrix[i].length; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
for(int i = 0; i < matrix.length; i++) {
for(int j = 0; j <matrix[i].length / 2; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[i][matrix.length-j-1];
matrix[i][matrix.length-j-1] = temp;
}
}
}
}