美文网首页
2019-09-08[剑指offer-]顺时针打印矩阵

2019-09-08[剑指offer-]顺时针打印矩阵

作者: Coding破耳 | 来源:发表于2019-11-15 22:23 被阅读0次

    题目描述

    输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

    class Solution {
    public:
        void printRound(vector<vector<int>>& matrix,int startrow,int startcol,
                           int endrow, int endcol,vector<int>& result)
        {
            for(int col = startcol; col <= endcol; col++)
            {
                result.push_back(matrix[startrow][col]);
            }
            
            if(startrow < endrow)
            {
                for(int row = startrow+1; row <= endrow; row++)
                {
                    result.push_back(matrix[row][endcol]);
                }
                
                if(endcol > startcol)
                {
                    for(int col = endcol-1; col >= startcol; col--)
                    {
                        result.push_back(matrix[endrow][col]);
                    }
                
                    if(endrow - startrow > 1)
                    {
                        for(int row = endrow-1; row > startrow; row--)
                        {
                            result.push_back(matrix[row][startcol]);
                        }
                    }
                }
            } 
        }
            
        
        vector<int> printMatrix(vector<vector<int> > matrix) {
            int maxrow = matrix.size();
            int maxcol = matrix[0].size();
            
            int x = min(maxrow,maxcol);
            
            int maxround = x/2+x%2;
            vector<int> result;
            for(int round = 0; round < maxround; round++)
            {
                printRound(matrix,round,round,maxrow-round-1,maxcol-round-1,result);
            }
            return result;
        }
    };
    

    相关文章

      网友评论

          本文标题:2019-09-08[剑指offer-]顺时针打印矩阵

          本文链接:https://www.haomeiwen.com/subject/kilpyctx.html