NC38 螺旋矩阵

题目描述:

给定一个m x n大小的矩阵(m行,n列),按螺旋的顺序返回矩阵中的所有元素。

解题分析:

采用模拟的方法,首先用left、top、right、bottom表示外面一圈的row、col的最小最大值,每次模拟一圈取值,然后left++、top++、right–、bottom++就表示往里一圈,然后继续模拟取值即可。需要注意的是这样每次模拟是至少是一个2*2的矩阵,所以需要考虑lefttop或者topbottom的情形。

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        if(matrix.size()==0)
            return {};
        vector<int> spiralOrderVec;
        int left=0, top=0, right=matrix[0].size()-1, bottom=matrix.size()-1;
        while(left<=right && top<=bottom){
            int row=top, col=left;
            if(left==right){
                while(row<=bottom){
                    spiralOrderVec.push_back(matrix[row][col]);
                    row++;
                }
                break;
            }
            else if(top==bottom){
                while(col<=right){
                    spiralOrderVec.push_back(matrix[row][col]);
                    col++;
                }
                break;
            }
            row=top, col=left;
            while(col<=right){
                spiralOrderVec.push_back(matrix[row][col]);
                col++;
            }
            row=top+1,col=right;
            while(row<=bottom){
                spiralOrderVec.push_back(matrix[row][right]);
                row++;
            }
            col=right-1,row=bottom;
            while(col>=left){
                spiralOrderVec.push_back(matrix[bottom][col]);
                col--;
            }
            row=bottom-1,col=left;
            while(row>top){
                spiralOrderVec.push_back(matrix[row][left]);
                row--;
            }
            left++,right--,top++,bottom--;
        }
        return spiralOrderVec;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值