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?
思路:这道题关键在于数组的操作问题上,如何保存中间变量,还有图片的旋转方法。首先将数组分为(行数/2)层,然后一层一层的进行旋转。
class Solution { public: void rotate(vector<vector<int> > &matrix) { if(matrix.size()==0||matrix[0].size()==0) return; int n=matrix.size(); int layer=n/2; for(int i=0;i<layer;i++) { for(int j=i;j<n-1-i;j++) { int temp=matrix[i][j]; matrix[i][j]=matrix[n-1-j][i]; matrix[n-1-j][i]=matrix[n-1-i][n-1-j]; matrix[n-1-i][n-1-j]=matrix[j][n-1-i]; matrix[j][n-1-i]=temp; } } } };