1. Topic introduction
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 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 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]
],
Rotate the input matrix in place so that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11 ]
]
Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/rotate-matrix-lcci
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Two, problem-solving ideas
The following figure shows the change that occurs when the square rectangle is rotated by 90°: 4->1->2->3->4 (representing the position change during 90 clockwise rotation)
In a given matrix, divide the area in the upper left corner, and each element in the area can be rotated by 90° after three exchanges . Let the dimension of the matrix be n.
- swap(matrix[i][j], matrix[j][n-i])
- swap(matrix[i][j], matrix[n-i][n-j])
- swap(matrix[i][j], matrix[n-j][i])
Three, problem-solving code
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int len = matrix.size();
int m = (len >> 1); //短边,注意要加括号
int n = (--len >> 1) + 1; //长边,考虑到N为奇数的情况,中心位置不发生变化
for(int i = 0; i < m; ++i)
{
for(int j = 0; j < n; ++j)
{
swap(matrix[i][j], matrix[j][len-i]);
swap(matrix[i][j], matrix[len-i][len-j]);
swap(matrix[i][j], matrix[len-j][i]);
}
}
}
};