c_cpp 54.螺旋矩阵

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 54.螺旋矩阵相关的知识,希望对你有一定的参考价值。

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> res;
        if (matrix.empty() || matrix.size() == 0 || matrix[0].empty() || matrix[0].size() == 0) return res;
        int rowBegin = 0;
        int rowEnd = matrix.size() - 1;
        int colBegin = 0;
        int colEnd = matrix[0].size() - 1;
        
        // loop over 2 ~ 4 steps
        while (rowBegin <= rowEnd && colBegin <= colEnd) {
            for (int i = colBegin; i <= colEnd; i++) {
                res.push_back(matrix[rowBegin][i]);
            }
            rowBegin++;   // all elements in first row ended
            
            for (int i = rowBegin; i <= rowEnd; i++) {
                res.push_back(matrix[i][colEnd]);
            }
            colEnd--;   // all elements in last row ended
            
            if (rowBegin <= rowEnd) {
                for (int i = colEnd; i >= colBegin; i--) {
                    res.push_back(matrix[rowEnd][i]);
                }
            }
            rowEnd--;
            
            if (colBegin <= colEnd) {
                for (int i = rowEnd; i >= rowBegin; i--) {
                    res.push_back(matrix[i][colBegin]);
                }
            }
            colBegin++;
        }
        
        return res;
    }
};

以上是关于c_cpp 54.螺旋矩阵的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp [螺旋矩阵II]:给定整数n,生成以螺旋顺序填充1到n2的元素的方阵。例如,给定n =

模拟LeetCode 54. 螺旋矩阵

模拟LeetCode 54. 螺旋矩阵

54. 螺旋矩阵

54. 螺旋矩阵

54. 螺旋矩阵