Leetcode notes: Rotate Image, leetcoderotate
I. Description
You are givenn×n2D matrix representing an image.
Rotate the image by 90 degrees (clockwise ).
Follow up: cocould you do this in-place?
Ii. Question Analysis
Since the image must be rotated 90 degrees clockwise, the simplest way is to draw a picture to observe the image after 90 degrees of rotation. After analysis, we can see that, rotating 90 degrees clockwise is to take the last row of the original image as the first column, the last row as the second column, and so on, the first row as the last column. If you do not consider the in-place condition, we can createn×nAnd then copy the rotated image back to the original image. The time complexity of this approach isO(n^2), The space complexity isO(n^2).
However, the question is expected to be implemented in-place. No matter what angle the image is selected, the points in the upper left corner can be considered as the origin of the coordinate system. Therefore, an image is abstracted3×3To find out some rules:
1 2 3
4 5 6
7 8 9
After 90 degrees clockwise rotation, the image abstraction is:
7 4 1
8 5 2
9 6 3
An equivalent transformation can be summarized:
First, each element of the matrix is exchanged along the main diagonal line;
1 2 3-1 4 7
4 5 6-> 2 5 8
7 8 9-3 6 9
Then, the elements in each column flip symmetric once along the horizontal midline. Here, the first and third columns are symmetric about the second column, so you only need to reconcile the first and third columns, you can get the result after 90 degrees of rotation.
1 4 7-7 4 1
2 5 8-> 8 5 2
3 6 9-9 6 3
Iii. Sample Code:
# Include <iostream> # include <vector> using namespace std; class Solution {public: void turnRightImage (vector <int> & image) {int imaSize = image. size (); // the elements below the main diagonal line and the elements above the main diagonal line change along the vertical direction of the main diagonal line for (int I = 1; I <imaSize; I ++) {for (int j = I-1; j> = 0; j --) swap (image [I] [j], image [j] [I]);} for (int k = 0; k <imaSize/2; k ++) {for (int l = 0; l <imaSize; l ++) swap (image [l] [k], image [l] [imaSize-k-1]) ;}};
One test result:
Iv. Summary
This question requires the in-place operation. in fact, we should consider the relationship between data and matrix before and after conversion. Based on the above analysis, we know that rotating an image 90 degrees clockwise is equivalent to switching each element of the matrix along the main diagonal line and then turning it once along the horizontal midline, or first, the matrix elements are flipped once along the horizontal midline, and then exchanged along the diagonal line, so that in-place operations can be performed, and the space complexity isO(1).
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.