Rotate Image
Question:
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?
Subscribe to see which companies asked this question
可以先旋转最外围一层,然后依次旋转里层:
1 class Solution { 2 public: 3 void rotate(vector<vector<int>>& matrix) { 4 int N=matrix.size(); 5 for(int layer=0;layer<N/2;layer++) 6 { 7 int first=layer; 8 int last=N-1-layer; 9 for(int i=first;i<last;i++) 10 { 11 int offset=i-first; 12 int top=matrix.at(first).at(i); //save top 13 matrix.at(first).at(i)=matrix.at(last-offset).at(first); //left->top 14 matrix.at(last-offset).at(first)=matrix.at(last).at(last-offset); //bottom->left 15 matrix.at(last).at(last-offset)=matrix.at(i).at(last); //right->bottom 16 matrix.at(i).at(last)=top; //top->right 17 } 18 } 19 20 } 21 };