leetcode 54.螺旋矩阵

leetcode 54.螺旋矩阵

题干

给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100

题解

转转输出。
遍历矩阵一遍,从左上角开始,先向右,再向下,再向左,再向上,如此循环。
可以发现前三次(右下左)的行宽和列高都和原矩阵一致,而后行宽和列高每次缩减1,模拟即可。
列向量的情况会有溢出的问题,所以特判,算是先天不足

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int rowCount = matrix.size();
        if(rowCount == 0) return {};
        int colCount = matrix[0].size();
        vector<int> ans;
        if(colCount == 1){
            for(auto i : matrix) ans.push_back(i[0]);
            return ans;
        }
        int n = (rowCount--) * (colCount--);
        int leftBound = 0,upperBound = 0;
        int currentStatus = 0;
        int rowIndex = 0,colIndex = 0;
        int decFlag = false;
        for(int i = 0 ; i < n ; ++i){
            //cout<<matrix[rowIndex][colIndex]<<' ';
            if(currentStatus == 0){
                ans.push_back(matrix[rowIndex][colIndex]);
                colIndex++;
                if(colIndex >= colCount){
                    currentStatus = 1;
                    colIndex = colCount;
                    if(decFlag) rowCount--; 
                } 
            }else if(currentStatus == 1){
                ans.push_back(matrix[rowIndex][colIndex]);
                rowIndex++;
                if(rowIndex >= rowCount){
                    currentStatus = 2;
                    rowIndex = rowCount;
                    if(decFlag) leftBound++;
                } 
            }else if(currentStatus == 2){
                ans.push_back(matrix[rowIndex][colIndex]);
                colIndex--;
                if(colIndex <= leftBound){
                    currentStatus = 3;
                    colIndex = leftBound;
                    decFlag = true;
                    upperBound++;   
                } 
            }else if(currentStatus == 3){
                ans.push_back(matrix[rowIndex][colIndex]);
                rowIndex--;
                //cout<<'*'<<rowIndex<<' '<<upperBound<<endl;
                if(rowIndex <= upperBound){
                    currentStatus = 0;
                    rowIndex = upperBound;
                    if(decFlag) colCount--;
                } 
            }
        }
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值