Description:
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
Link:
https://leetcode.com/problems/rotate-image/#/description
解题方法:
先将矩阵按照逆对角线翻转,在按照上下的中线翻转即可。
Tips:
注意在翻转的时候只用遍历一半的元素,如果遍历所有的元素则不会有变换(因为在遍历另一半的时候又会被翻转回来)。
Time Complexity:
O(N^2)
完整代码:
void rotate(vector<vector<int>>& matrix)
{
int len = matrix.size();
if(len == 0)
return;
for(int i = 0; i < len; i++)
for(int j = 0; j < len-i; j++) //只能交换逆对角线一边的数
Swap(matrix[i][j], matrix[len-1-j][len-1-i]);
for(int i = 0; i < len/2; i++)
for(int j = 0; j < len; j++) //只能交换一半的数
Swap(matrix[i][j], matrix[len-1-i][j]);
}
void Swap(int& a, int& b)
{
int temp = a;
a = b;
b = temp;
}