顺时针打印矩阵

2019-07-29  本文已影响0人  HamletSunS

思路:

class Solution {
public:
    vector<int> printMatrix(vector<vector<int> > matrix) {
        vector<int> ret;
        int row=matrix.size();
        if(row==0)
            return ret;
        int col=matrix[0].size();
        if(col==0)
            return ret;
        
        int left=0,right=col-1,top=0,bottom=row-1;
        while(left<=right && top<=bottom){
            //left -> right
            for(int i=left;i<=right;++i)
                ret.push_back(matrix[top][i]);
            //top->bottom
            for(int i=top+1;i<=bottom;i++)
                ret.push_back(matrix[i][right]);
            //right->left
            if(top<bottom){
                for(int i=right-1;i>=left;i--)
                    ret.push_back(matrix[bottom][i]);
            }
            
            //bottom->top
            if(left<right){
                for(int i=bottom-1;i>=top+1;i--)
                ret.push_back(matrix[i][left]);
            }
            
            left++;
            right--;
            top++;
            bottom--;
        }
        return ret;
    };    
};
上一篇下一篇

猜你喜欢

热点阅读