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?
思路:
每次转着圈挪四个元素,这步只需要一个int的额外空间,想象一个方阵
哦不好意思,这个太不专业了,咱换个大一点6×6的
草图上比划比划第二层的元素怎么移动,一次Accept的感觉好爽
代码:
1 void rotate(vector<vector<int> > &matrix) { 2 int n = matrix.size(); 3 if(n < 2) return; 4 5 for(int layer = 0; layer < n/2; layer++){ 6 for(int i = layer; i < n-1-layer; i++){//避免重复处理n-1-layer 7 int leftTop = matrix[layer][i];//注意二维矩阵的(i,j)index与数学坐标(x,y)中是相反的 8 matrix[layer][i] = matrix[n-1-i][layer]; //先在纸上想清楚赋值的先后循序 9 matrix[n-1-i][layer] = matrix[n-1-layer][n-1-i]; 10 matrix[n-1-layer][n-1-i] = matrix[i][n-1-layer]; 11 matrix[i][n-1-layer] = leftTop; 12 } 13 } 14 }