顺时针打印矩阵

题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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.
思路:设置4个标记,分别为上下左右。每次输出完都更新标记,while的循环条件一定要left <= right &&bottom>=top  ,要加=,因为可能矩阵为只有1行或只有一列。内部的循环条件也是。
代码:
class Solution {
public:
    vector<int> printMatrix(vector<vector<int> > matrix) {
        int row = matrix.size();
        int column = matrix[0].size();
        vector<int> sum;
        if(row == 0 || column == 0)
            return sum;
        int left = 0;
        int right = column-1;
        int top = 0;
        int bottom = row-1;
        while(top <= bottom && right >= left)
        {
            for(int i  = left; i <= right;i++)
                sum.push_back(matrix[top][i]);
            for(int i = top+1; i <= bottom; i++)
                sum.push_back(matrix[i][right]);
            if(top != bottom)
            for(int i = right-1; i >= left;i--)
                sum.push_back(matrix[bottom][i]);
            if(right != left)
            for(int i = bottom-1;i > top;i--)
                sum.push_back(matrix[i][left]);
            top++;bottom--;left++;right--;
        }
        return sum;
    }
};
原文地址:https://www.cnblogs.com/Lune-Qiu/p/9094484.html