Topic link
Title description:
Give you an image represented by an N × N matrix, where each pixel is 4 bytes in size. Please design an algorithm to rotate the image by 90 degrees.
Can it be done without taking up additional memory space?
Example 1:
Given matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
rotate the input matrix in place to make it become:
[
[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]
],
rotate input in place Matrix so that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
In-situ modification
Find the law and add a little impression of college linear algebra. . .
- Matrix transpose (swap elements up and down along the main diagonal);
- Each line is flipped left and right by the center point.
Code
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int len = matrix.size();
for(int i = 0; i < len - 1; i++)
for(int j = i + 1; j < len; j++)
swap(matrix[i][j], matrix[j][i]);
int mid = len / 2;
for(int i = 0; i < len; i++){
for(int j = 0; j < mid; j++){
swap(matrix[i][j], matrix[i][len - 1 - j]);
}
}
return;
}
};
If there are mistakes or not rigorous, please correct me, thank you very much.
My blog: http://breadhunter.gitee.io