剑指offer 019、顺时针打印矩阵

剑指offer 019、顺时针打印矩阵

题目

image-20210913125649569

题解

自己做时思路都是对的,但是在边界的控制不到位,以至于旋转到矩阵最里层出现部分数字未打印。下面参考了一下大佬的处理方法才做出来

对于后面两个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 || !col) return res;
        
        // 四个变量用来限制上下左右打印范围
        int left = 0, right = col - 1;
        int top = 0, bottom = row - 1;
        
        while (left <= right && top <= bottom) {
            // left to right
            for (int i = left; i <= right; ++i) {
                res.push_back(matrix[top][i]);
            }
            // top to bottom
            for (int i = top + 1; i <= bottom; ++i) {
                res.push_back(matrix[i][right]);
            }
            // 还要加两个限制条件:top < bottom 和 left < right
            // right to left
            for (int i = right - 1; i >= left && top < bottom; --i) {
                res.push_back(matrix[bottom][i]);
            }
            // bottom to top
            for (int i = bottom - 1; i > top && left < right; --i) {    // 注意这里是 i > top
                res.push_back(matrix[i][left]);
            }
            left++, right--;
            top++, bottom--;
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ClimberCoding

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值