剑指offer-顺时针打印矩阵

每个人有不同的方法,我用四个变量标记边界

class Solution {
public:
    vector<int> printMatrix(vector<vector<int> > matrix) {
        vector<int> res;
        int l,r,t,b;
        l = 0, r = matrix[0].size() - 1, t = 0, b = matrix.size() - 1;
        while(r >= l && b >= t){
            for(int i = l; i <= r; ++i){
                res.push_back(matrix[t][i]);
            }
            t++;
            if(t > b) break;
            for(int i = t; i <= b; ++i){
                res.push_back(matrix[i][r]);
            }
            r--;
            if(l > r) break;
            for(int i = r; i >= l; --i){
                res.push_back(matrix[b][i]);
            }
            b--;
            if(t > b) break;
            for(int i = b; i >= t; --i){
                res.push_back(matrix[i][l]);
            }
            l++;
        }
        return res;
    }
};
View Code

 

posted @ 2017-10-13 18:31  Deaglepc  阅读(244)  评论(0编辑  收藏  举报