20行C++代码实现矩阵顺时针打印

顺时针打印矩阵

http://www.nowcoder.com/questionTerminal/9b4c81a02cd34f76be2659fa0d54342a

class Solution {
public:
    vector<int> printMatrix(vector<vector<int> > mat) {
        vector<int> output;
        int cb = 0, ce = mat[0].size()-1, rb = 0, re = mat.size()-1,step = -1,
        r,c, elementNumber = mat[0].size() * mat.size();
        while( output.size() < elementNumber){
            step *= -1;
            for(r = rb, c = cb; c != ce + step; c += step)
                output.emplace_back(mat[r][c]);
            rb += step;
            for(c = ce,r = rb; r != re + step; r += step)
                output.emplace_back(mat[r][c]);
            ce -= step;
            swap(rb,re);
            swap(cb,ce);
        }
        return output;
    }
};

改成迭代器实现快 1ms

class Solution {
public:
    vector<int> printMatrix(vector<vector<int> > mat) {
        vector<int> output;
        vector<vector<int> >::iterator r;
        int rb = 0, re = mat.size()-1, cb = 0, ce = mat[0].size()-1;
        vector<int>::iterator c;
        int step = -1, elementNumber = mat[0].size() * mat.size();
        while(output.size() < elementNumber){
            step *= -1;
            for(r = mat.begin()+rb, c = (*r).begin() + cb;
                c != (*r).beg***ep; c += step)
                output.emplace_back(*c);
            rb += step;
            for(r = mat.begin()+rb; r != mat.begin() + re + step; r += step)
                output.emplace_back( *((*r).begin()+ce) );
            ce -= step;
            swap(rb,re);
            swap(cb,ce);
        }
        return output;
    }
};
全部评论

相关推荐

野猪不是猪🐗:把你的学校加黑,加粗,斜体,下划线,描边,内阴影,内发光,投影,外发光,再上渐变色,居中,放大到最大字号,再把简历里其它内容删了,就行了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务