[剑指offer] 顺时针打印矩阵

题目描述

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

本来是用的变换坐标数组{{0,1},{1,0},{0,-1},{-1,0}}来直接两层循环的,但是编译说是数组越界什么的,

换了手打四个循环还是越界,后来发现是只判断了左边界小于等于右边界而没有判断上边界小于等于下边界,

然后还有注意下有可能会出现同一行或者同一列打印两遍的情况,要进行判断。

class Solution {
public:
    vector<int> printMatrix(vector<vector<int> > matrix) {
        vector<int> re;
        if (matrix.size() == 0 || matrix[0].size() == 0) return re;
        int left = 0, right = matrix[0].size() - 1;
        int top = 0, bottom = matrix.size() - 1;
        // 横竖都要判断,因为矩形不一定为正方形
        while (left <= right && top <= bottom) {
            for (int i = left; i <= right; i++) re.push_back(matrix[top][i]);
            for (int i = top + 1; i <= bottom; i++) re.push_back(matrix[i][right]); 
            // 防止top和bottom相等时同一行打印两次
            // 防止left和right相等时同一列打印两次
            if (top != bottom) for (int i = right - 1; i >= left; i--) re.push_back(matrix[bottom][i]);
            if (left != right) for (int i = bottom - 1; i >= top+1; i--) re.push_back(matrix[i][left]);
            top++,bottom--,left++,right--;
        }
        return re;
    }
};
原文地址:https://www.cnblogs.com/zmj97/p/7906484.html