You are givenNXN2D matrix representing an image.
Rotate the image by 90 degrees (clockwise ).
Follow up:
Cocould you do this in-place
The N * n matrix rotates 90 degrees clockwise. Law a [I] [J] --> A [J] [n-I]
Idea 1. Copy Data row by row according to the rule. A new two-dimensional array needs to be created, with a slightly higher space complexity.
2. Replace the elements and target positions one by one according to the rule. It is found that the coordinates will return to the starting position every four times.
Take the 4*4 matrix as an example. A [0] [0] --> A [0] [3] --> A [3] [3] --> A [3] [0] ---> A [0] [0]
Each row is traversed (n-1), and the square composed of the elements in the outermost ring has reached the goal.
Scale down the square and replace it by line.
1 public class Solution { 2 public void rotate(int[][] matrix) { 3 if(matrix == null ||matrix.length <= 1){ 4 return; 5 } 6 int n = matrix.length; 7 int rectangleLen = n; 8 int row = 0; 9 while(rectangleLen >=2){10 for(int i =row;i<= n-2 - row ;i++){11 rotateRectangle(matrix,n,row,i); 12 }13 rectangleLen-= 2;14 row ++;15 }16 }17 18 public void rotateRectangle(int[][] matrix,int n,int x_pos,int y_pos){19 int temp = matrix[x_pos][y_pos];20 int target = 0;21 int temp_pos = 0;22 for(int i=0;i<4;i++){23 target = temp;24 //target position25 temp_pos = x_pos;26 x_pos = y_pos;27 y_pos = n - 1 - temp_pos;28 temp = matrix[x_pos][y_pos];29 //replace30 matrix[x_pos][y_pos] = target; 31 }32 }33 }
Leetcode-rotate Image