Title Description Input a matrix and print out each number in clockwise order from the outside to the inside. For example, if you enter the following 4 X 4 matrix: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Print out the number

class Solution {
public:   
    vector<int> printMatrix(vector<vector<int> > matrix) {
    vector<int> save;
    int length;
    int width;
    int count;
    int start=0;    
    length=matrix.size();
    width=matrix[0].size();
    count=length*width;
    while(count){
        for(int i=start;i<width;i++){
            save.push_back(matrix[start][i]);
            count--;
            if(count==0)
             return save;   
        }
        for(int i=start+1;i<length;i++){
           save.push_back(matrix[i][width-1]);
           count--;
              if(count==0)
             return save;   
           }
        for(int i=width-2;i>=start;i--){
             save.push_back(matrix[length-1][i]);
             count--;
              if(count==0)
             return save;   
          }
        for(int i=length-2;i>start;i--){
             save.push_back(matrix[i][start]);
          count--;
              if(count==0)
             return save;   
          }
        length --;
		width --;
		start ++;   
    }  
       return save;     
    }   
};

 

Guess you like

Origin blog.csdn.net/m0_38099328/article/details/85851738