题解 | #顺时针打印矩阵#

顺时针打印矩阵

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

模拟顺时针遍历矩阵的过层,先求出矩阵有多少层(圈),然后按层遍历。
每次都从该圈左上角的点按照向右,向下,向左,最后向上的顺序遍历,然后按相同顺序遍历内圈。
这种做法由于默认了给出的矩阵最少有两行两列,所以在遇到单行或单列时容易出现问题,为解决这一问题,在遍历完右和下时,判断结果数组内的元素个数是否已与给定矩阵的元素个数相等,若等则直接返回。
在这种按圈遍历的做法中,根据矩阵的不同,在遍历完后容易在中间遗漏一些元素未遍历。起初在研究什么样的矩阵会在遍历完后中间仍有元素未遍历这个问题上花了很多时间,而且并未总结出可靠规律,最后索性不研究这一问题,直接用结果数组中的元素数量是否小于矩阵元素的数量来判断,若小于,则说明有遗漏元素,继续遍历,否则返回。

class Solution {
public:
    vector<int> printMatrix(vector<vector<int> > matrix) {
        vector<int> result;
        if(matrix.empty()){
            return result;
        }
        int row = 0;
        int col = 0;
        int layer = matrix.size()/2 < matrix.at(0).size()/2 ? matrix.size()/2 : matrix.at(0).size()/2;
        if(!layer){
            layer = 1;
        }
        int round = 0;
        while(round < layer){
            while(col < matrix.at(0).size() - round){
                result.push_back(matrix.at(row).at(col));
                col++;
            }
            col--;
            row++;
            while(row < matrix.size() - round){
                result.push_back(matrix.at(row).at(col));
                row++;
            }
            row--;
            col--;
            if(result.size() == matrix.size() * matrix.at(0).size()){
                return result;
            }
            while(col >= round){
                result.push_back(matrix.at(row).at(col));
                col--;
            }
            col++;
            row--;
            while(row > round){
                result.push_back(matrix.at(row).at(col));
                row--;
            }
            row++;
            col++;
            round++;
        }
        if(result.size() < matrix.size() * matrix.at(0).size()){
            while(col < matrix.at(0).size() - round){
                result.push_back(matrix.at(row).at(col));
                col++;
            }
            col--;
            row++;
            while(row < matrix.size() - round){
                result.push_back(matrix.at(row).at(col));
                row++;
            }
        }
        return result;
    }
};
全部评论

相关推荐

风中翠竹:真的真的真的没有kpi。。。面试官是没有任何kpi的,捞是真的想试试看这个行不行,碰碰运气,或者是面试官比较闲现在,没事捞个人看看。kpi算HR那边,但是只有你入职了,kpi才作数,面试是没有的。
双非有机会进大厂吗
点赞 评论 收藏
分享
05-29 22:11
门头沟学院 Java
Elastic90:抛开学历造假不谈,这公司的招聘需求也挺怪的,Java开发还要求你有图文识别、移动端开发和c++的经验,有点逆天了。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务