剑指offer之顺时针打印矩阵

顺时针打印矩阵

https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a?tpId=13&&tqId=11172&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题目

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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:
    vector<int> printMatrix(vector<vector<int> > matrix) {
    vector<int> MatrixValue;
    int length = matrix.size();
    int beginCol = 0, endCol = matrix.size()-1, beginRow = 0, endRow = matrix[0].size()-1;
    while (beginCol <= endCol && beginRow <= endRow)
    {
        int TimesCol = endCol - beginCol;
        int TimesRow = endRow - beginRow;

        if (beginCol == endCol && beginRow != endRow)
        {
            for (int j = beginRow; j <= endRow; j++)
            {
                if (j != endRow)
                {
                    cout << matrix[beginCol][j] << ",";
                    MatrixValue.push_back(matrix[beginCol][j]);
                }
                else
                {
                    cout << matrix[beginCol][j];
                    MatrixValue.push_back(matrix[beginCol][j]);
                }

            }
        }
        else if (beginRow == endRow)
        {
            for (int i = beginCol; i <= endCol; i++)
            {

                if (i != endCol)
                {
                    cout << matrix[i][beginRow] << ",";
                    MatrixValue.push_back(matrix[i][beginRow]);
                }
                else
                {
                    cout << matrix[i][beginRow];
                    MatrixValue.push_back(matrix[i][beginRow]);
                }
            }
        }
        else
        {
            for (int iF = 0; iF < TimesRow; iF++)
            {
                cout << matrix[beginCol][beginRow + iF] << ",";
                MatrixValue.push_back(matrix[beginCol][beginRow + iF]);
            }
            for (int iS = 0; iS < TimesCol; iS++)
            {
                cout << matrix[beginCol + iS][endRow] << ",";
                MatrixValue.push_back(matrix[beginCol + iS][endRow]);
            }
            for (int iT = 0; iT < TimesRow; iT++)
            {
                cout << matrix[endCol][endRow - iT] << ",";
                MatrixValue.push_back(matrix[endCol][endRow - iT]);
            }
            for (int iFo = 0; iFo < TimesCol; iFo++)
            {
                cout << matrix[endCol - iFo][beginRow] << ",";
                MatrixValue.push_back(matrix[endCol - iFo][beginRow]);
            }
        }

        beginCol++;
        endCol--;
        beginRow++;
        endRow--;
    }

    return MatrixValue;
    }
};
全部评论

相关推荐

菜鸡芊寻:再找找兄弟 我两年前跟你一样 别气馁
点赞 评论 收藏
分享
牛客963010790号:一般是hr拿着老板账号在招人不是真是老板招
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务