顺时针打印矩阵

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

例如,如果输入如下矩阵:

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。

基本思想:因为是顺时针打印一个数组,我们能够知道,左上角的坐标中行标和列表中总是相同的,因此,假设选取左上角坐标为(start,start)为分析的目标。

     循环的条件为column>start*2&&row>start*2

值得注意的是,在判断数组是否需要从上向下,从右到左,从下到上打印时,要判断所剩的行数,是否满足条件。

第一行输入为数组的列和行

例如:

4 4

1 2 3 4

5 6 7 8

9 10 11 12

13 14 15 16

具体代码:

#include<bits/stdc++.h>
using namespace std;

class Solution {
public:
    vector<int> printMatrix(vector<vector<int> > matrix) {
        vector<int> res;
        int row = matrix.size();
        int column = matrix[0].size();
        int endX = column-1;
        int endY = row-1;
        int start =0;
        if(row<=0&&column<=0)
            return res;
            cout<<"999"<<endl;
        while(row>start*2&&column>start*2)
        {
            //从左往右
            for(int i=start;i<=endX;i++)
            {
                res.push_back(matrix[start][i]);
            }
            //从上往下
            if(start<endY)//注意这种边界条件
            {
                for(int i=start+1;i<=endY;i++)
                {
                    res.push_back(matrix[i][endX]);
                }
            }
            //从右往左打印
            if(start<endX&&start<endY)//注意边界条件
            {
                for(int i=endX-1;i>=start;i--)
                {
                    res.push_back(matrix[endY][i]);
                }
            }

            //从下往上   
            if(start<endX&&start<endY-1)//注意边界条件
            {
                for(int i=endY-1;i>start;i--)
                {
                    cout<<matrix[i][start]<<endl;
                    res.push_back(matrix[i][start]);
                }
            }
            start++;
            endY--;
            endX--;
        }
        return res;
    }
};

int main()
{
    int n;
    int m;
    cin>>n>>m;
    vector<int> str(n);
    vector<vector<int> > res;
    vector<int> result;
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            cin>>str[j];
        }
        res.push_back(str);
    }
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            cout<<res[i][j];
        }
        cout<<endl;
    }

    Solution solution;
    result= solution.printMatrix(res);
    for(int i=0;i<result.size();i++)
    {
        cout<<result[i]<<" ";
    }
    cout<<endl;
    return 0;
}