LeetCode刷题日记 剑指 Offer 29. 顺时针打印矩阵

之前几天在看吴恩达,LeetCode停了几天,今天重新开始,希望之后每天能抽出时间写几道。

这道题目是剑指offer上的第29题,顺势正打印矩阵。题目给出一个由数组构成的矩阵,要求顺时针顺序从里到外打印出每一个数字,代码如下:

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        if (matrix.size() == 0 || matrix[0].size() == 0) {
            return {};
        } //判断举证是否为空
        int n = matrix.size();//读取举证的列数
        int m = matrix[0].size();//读取矩阵的行数
        int size = m*n;//矩阵总共含有的元素个数
        vector<int> answer(size);//创建答案数组
        int count = 0;//创建下表
        //创建矩阵的上下左右,循环一圈以后,上下左右的值分别向内收缩
        int left = 0;
        int right = m - 1;
        int top = 0;
        int bottom = n - 1;
        while(right >= left && bottom >= top)
        {
            for(int column = left; column <= right ; ++column)
            {
                answer[count++] = matrix[top][column];
            }
            for(int row = top + 1; row <= bottom; ++row)
            {
                answer[count++] = matrix[row][right];
            }
            if(right > left && bottom > top)
            {
                for(int column = right - 1; column >= left; --column)
                {
                    answer[count++] = matrix[bottom][column];
                }
                for(int row = bottom - 1; row > top; --row)
                {
                    answer[count++] = matrix[row][left];
                }
            }
            //向内收随
            left++;
            right--;
            top++;
            bottom--;
        }
        return answer;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值