顺时针打印矩阵

题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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.
#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>

using namespace std;
/*

    思想,用左上和右下的坐标定位出一次要旋转打印的数据,一次旋转打印结束后,往对角分别前进和后退一个单位。
    提交代码时,主要的问题出在没有控制好后两个for循环,需要加入条件判断,防止出现单行或者单列的情况。
 */

class Solution
{
public:
    vector<int> printMatrix(vector<vector<int> > matrix)
    {
        int row = matrix.size();  //行数
        int col = matrix[0].size();  //列数
        vector<int> res;
        if(row == 0||col == 0)
            return res;
        int left = 0,top = 0, right  = col-1,bottom = row-1;   //左上(left,top),右下(right,bottom)
        //右下左上的4个循环
        while(left <=right&&top <=bottom)
        {
            //从左到右
            for(int i = left; i<=right; ++i)
            {
                res.push_back(matrix[top][i]);
            }
            //从上到下
            for(int i=top+1; i<=bottom; ++i)
            {
                res.push_back(matrix[i][right]);
            }
            //从右到左
            if(top!=bottom)
                for(int i=right-1; i>=left; --i)
                {
                    res.push_back(matrix[bottom][i]);
                }
            //从下到上
            if(left!=right-1)
                for(int i=bottom-1; i>top; --i)
                {
                    res.push_back(matrix[i][left]);
                }
            left++,top++,right--,bottom--;
        }
        /*
        for(int i=0; i<res.size(); i++)
        {
            cout<<res[i];
        }
        */
        return res;
    }
};
int main()
{
    Solution s;
    vector< vector<int> > matrix;
    vector<int> vec1,vec2,vec3,vec4;
    vector<int> result;

    for(int i=1; i<=4; i++)
    {
        vec1.push_back(i);
    }
    matrix.push_back(vec1);

    for(int i=5; i<=8; i++)
    {
        vec2.push_back(i);
    }
    matrix.push_back(vec2);
    for(int i=9; i<=12; i++)
    {
        vec3.push_back(i);
    }
    matrix.push_back(vec3);
    for(int i=13; i<=16; i++)
    {
        vec4.push_back(i);
    }
    matrix.push_back(vec4);
    /*
    for(int i=0;i<matrix.size();i++)
    {
        for(int j=0;j<matrix[0].size();j++)
        {
            cout<<matrix[i][j];
        }
    }
    */

    result = s.printMatrix(matrix);

    for(int i=0; i<result.size(); i++)
    {
        cout<<result[i];
    }
    return 0;
}
原文地址:https://www.cnblogs.com/dshn/p/9200498.html