The sword refers to Offer_Programming questions_19

Topic description

Enter a matrix and print each number in clockwise order from the outside to the inside. For example, if you enter the following matrix: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Then print the number 1 in turn, 2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
 
class Solution {
public:
    vector<int> printMatrix(vector<vector<int> > matrix) {
        vector<int>vt;
        int row = matrix.size();
        int col = matrix[0].size();
        int ri=0,rj=row-1,ci=0,cj=col-1,i=0,j=0;
        while(ci<=cj&&ri<=rj){
            for(j=ci;j<=cj;j++){
                vt.push_back(matrix[ri][j]);
            }
            ri++;
            if(ci>cj||ri>rj)break;
            for(i=ri;i<=rj;i++){
                vt.push_back(matrix[i][cj]);
            }
            cj--;
            if(ci>cj||ri>rj)break;
            for(j=cj;j>=ci;j--){
                vt.push_back(matrix[rj][j]);
            }
            rj--;
            if(ci>cj||ri>rj)break;
            for(i=rj;i>=ri;i--){
                vt.push_back(matrix[i][ci]);
            }
            ci ++;
        }
        return vt;
    }
};

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324914916&siteId=291194637