[leetcode] Rotate Image

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Follow up:
Can u do this in place?

思路:从外圈四边开始转,总是(i,j)--> (j,n-1-i)。递归到内圈

class Solution {
public:
    void rotate(vector<vector<int> > &matrix) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        rotateedges(matrix, matrix.at(0).size(),0);
    }
    
    void rotateedges(vector<vector<int>> &matrix, int n,int start)
    {
       if(n<=1)
            return;
            
       int tobereplaced, replace,indexi,indexj;
       
       int startrow=start;
       int endrow=matrix.at(0).size()-startrow-1;
       
       for(int i=0; i<n-1; i++)
       {
           
           indexi=0;   
           indexj=i;
           
           tobereplaced=matrix.at(indexi+startrow).at(indexj+startrow);
           for(int j=0;j<4;j++)
           {
              replace=tobereplaced;
              int previndexi=indexi;
              indexi=indexj;
              indexj=n-1-previndexi;
              tobereplaced=matrix.at(indexi+startrow).at(indexj+startrow);
              matrix.at(indexi+startrow).at(indexj+startrow)=replace;
           }
       }
       
       rotateedges(matrix,n-2,start+1);
     
    }
    
};


你可能感兴趣的:([leetcode] Rotate Image)