标签:
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?
将一个矩阵顺时针旋转90度。
class Solution { public: void rotate(vector<vector<int>>& matrix) { if(matrix.size()==1) return; int n=matrix.size(); for(int i=0;i<n;i++) { for(int j=0;j<i;j++) { int temp=matrix[i][j]; matrix[i][j]=matrix[j][i]; matrix[j][i]=temp; } } vector<vector<int>> danwei; vector<int> temp1(n,0); vector<int> temp2; for(int i=0;i<n;i++) { temp2=temp1; temp2[n-1-i]=1; danwei.push_back(temp2); } for(int i=0;i<n;i++) { temp2.clear(); for(int j=0;j<n;j++) { int ji=0; for(int t=0;t<n;t++) ji+=matrix[i][t]*danwei[t][j]; temp2.push_back(ji); } matrix[i]=temp2; } } };方法二:
class Solution { public: void rotate(vector<vector<int>>& matrix) { if(matrix.size()==1) return; int n=matrix.size(); for(int i=0;i<n;i++) { for(int j=0;j<n-1-i;j++) { int temp=matrix[i][j]; matrix[i][j]=matrix[n-1-j][n-1-i]; matrix[n-1-j][n-1-i]=temp; } } vector<int> temp1; for(int i=0;i<n/2;i++) { temp1=matrix[i]; matrix[i]=matrix[n-1-i]; matrix[n-1-i]=temp1; } } };
标签:
原文地址:http://blog.csdn.net/sinat_24520925/article/details/46427435