剑指 Offer 29. 顺时针打印矩阵

/*
1.和54. 螺旋矩阵 一样,区别在于这里可能为空的矩阵,需要判断一下
思路:定义上下左右边界,模拟循环转圈,需要注意最后只剩一行或一列的时候需要添加额外的判断
因为每次都是先往右走和先往下走,所以往右走和往下走的路一定是没走过的路,不需要加 if 判断;往左走的时候,如果 top == bottom,那么会重复走之前从左往右走过的路,所以需要加上 top < bottom 的判断,同理往上走也一样。
*/
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        if (matrix.empty()) return {}; //需要考虑矩阵为空的时候,难以想到
        vector<int> result;
        int rows = matrix.size(), colums = matrix[0].size();
        //定义上下左右边界
        int left = 0, right = colums - 1, top = 0, bottom = rows -1;
        //做判断
        if(rows == 0 || colums == 0) return result;
        //开始循环便利
        while(left <= right && top <= bottom){
            for(int colum = left; colum <= right; colum++){
                result.push_back(matrix[top][colum]);
            }

            for(int row = top + 1; row <= bottom; row++){
                result.push_back(matrix[row][right]);
            }
            //难点在这,需要判断一下从右到左,从下到上的情况(单行或者单列的情况)
            if(left < right && top < bottom)
            {
            for(int colum = right - 1; colum > left; colum--){
                result.push_back(matrix[bottom][colum]);
            }

            for(int row = bottom; row > top; row--){
                result.push_back(matrix[row][left]);
            }
            }
            left++, right--;
            top++, bottom--;

        }
        return result;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值