标签:style blog http io ar color os sp for
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?
Array
1 | 2 | 3 | 1 |
3 | 4 | 4 | 2 |
2 | 4 | 4 | 3 |
1 | 3 | 2 | 1 |
1 #include <iostream> 2 #include <vector> 3 #include <iterator> 4 using namespace std; 5 6 class Solution { 7 public: 8 void rotate(vector<vector<int> > &matrix) { 9 int n =matrix.size(); 10 if(n<2) return ; 11 for(int i=0;i<(n+1)/2;i++){ 12 for(int len=0;len<=n-2*(i+1);len++){ 13 int temp = matrix[i][i+len]; 14 matrix[i][i+len] = matrix[n-1-i-len][i]; 15 matrix[n-1-i-len][i] = matrix[n-1-i][n-1-i-len]; 16 matrix[n-1-i][n-1-i-len] = matrix[i+len][n-i-1]; 17 matrix[i+len][n-i-1] = temp; 18 } 19 } 20 } 21 }; 22 23 int main() 24 { 25 vector<vector<int> > matrix; 26 vector<int> tempm; 27 int cnt =1; 28 for(int i=1;i<9;i++){ 29 for(int j=1;j<9;j++) 30 tempm.push_back(cnt++); 31 matrix.push_back(tempm); 32 tempm.clear(); 33 } 34 Solution sol; 35 sol.rotate(matrix); 36 for(int i=0;i<matrix.size();i++){ 37 copy(matrix[i].begin(),matrix[i].end(),ostream_iterator<int>(cout," ")); 38 cout<<endl; 39 } 40 41 return 0; 42 }
标签:style blog http io ar color os sp for
原文地址:http://www.cnblogs.com/Azhu/p/4128361.html