标签:
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?
Solution
1 class Solution { 2 public: 3 void rotate(vector<vector<int>>& matrix) { 4 int i=0; 5 for(auto iter1=matrix.begin();iter1!=matrix.end();i++,iter1++) 6 { int j=i+1; 7 for(auto iter2=iter1+1;iter2<matrix.end();j++,iter2++) 8 { 9 int temp=*((*iter1).begin()+j); 10 *((*iter1).begin()+j)=*((*iter2).begin()+i); 11 *((*iter2).begin()+i)=temp; 12 } 13 } 14 // row to col 15 vector< vector<int> >col_matrix; 16 for(int i=0;i<matrix.size();i++) 17 { 18 vector<int> p; 19 for(int j=0;j<matrix.size();j++) 20 { 21 p.push_back(matrix[j][i]); 22 //*((*(matrix.begin()+i)).begin()+j)=matrix[j][i]; 23 } 24 //*(matrix.begin()+i)=p; 25 col_matrix.push_back(p); 26 } 27 matrix=col_matrix; 28 //reverse 29 reverse(matrix.begin(),matrix.end()); 30 // 31 i=0; 32 for(auto iter1=matrix.begin();iter1!=matrix.end();i++,iter1++) 33 { int j=i+1; 34 for(auto iter2=iter1+1;iter2<matrix.end();j++,iter2++) 35 { 36 int temp=*((*iter1).begin()+j); 37 *((*iter1).begin()+j)=*((*iter2).begin()+i); 38 *((*iter2).begin()+i)=temp; 39 } 40 } 41 } 42 };
标签:
原文地址:http://www.cnblogs.com/riden/p/4631564.html