题目
代码
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n=matrix.size();
for(int i=0;i<n;i++)
{
for(int j=0;j<i;j++)
{
std::swap(matrix[i][j],matrix[j][i]);
}
}
for(int i=0;i<n;i++)
{
reverse(matrix[i].begin(),matrix[i].end());
}
}
};
思路
这道题我当时没想出来,在讨论区看到这个答案的代码非常完美。下面截取一段解释(看懂了这个解释基本也就理解了这个算法的思路,自己在纸上模拟一下2或者3阶的解法步骤即可):
Best answer to this problem! Although at first I found it really hard to figure out why it works, but now I think I have got the beauty behind the code and here is my understanding.
Consider the transformation of coordinates in a 4x4 matrix after rotation :
(0,0) -> (0,3)
(0,1) -> (1,3)
(0,2) -> (2,3)
...
and for a NxN matrix, we have the transform :
( i , j ) -> ( j , N - i -1 )
Based on this, you can perform ( i , j ) -> ( j , i ) by transpose the matrix, and reverse each row to perform ( j , i ) -> ( j , N - i - 1).It's a little bit hard to figure out why ( i , j ) -> ( j , N - i -1 ) after rotation. From another perspective, imagine that there is a square (side length = n) and it has a rectangular coordinate system along the lower-left corner, and the matrix is plotted on the square. The effects of rotating matrix is equivalent to the rotation and translation of the coordinate system to the lower-right corner of square, and the coordinates of points ( i , j ) on the matrix can be easily calculated to be exactly ( j , N - i -1 ). If still confused, just grab a pen and draw it on paper and you will get it.