题目

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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;
    }
};