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; } };