Subject description:
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:
由于:matrix[x][y] = matrix[length-1-y][x];
matrix[length-1-y][x] = matrix[length-1-x][length-1-y];
matrix[length-1-x][length-1-y] = matrix[y][length-1-x];
matrix[y][length-1-x] = matrix[x][y];
According to the principle of space-saving, using a four rotation region, as shown:
package array; public class L48 { public static void rotate(int[][] matrix) { for(int index_x = 0;index_x <=(matrix.length-1)/2;index_x++){ for(int index_y = index_x;index_y < matrix.length -1 - index_x;index_y++){ int temp = matrix[index_x][index_y]; matrix[index_x][index_y] = matrix[matrix.length-1-index_y][index_x]; matrix[matrix.length-1-index_y][index_x] = matrix[matrix.length-1-index_x][matrix.length-1-index_y]; matrix[matrix.length-1-index_x][matrix.length-1-index_y] = matrix[index_y][matrix.length-1-index_x]; matrix[index_y][matrix.length-1-index_x] = temp; } } } public static void main(String[] args) { int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}}; rotate(matrix); for(int index = 0;index<matrix.length;index++){ for(int de = 0;de <matrix.length;de++){ System.out.println(matrix[index][de]); } } } }