• 54. Spiral Matrix (Graph)


    Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

    For example,
    Given the following matrix:

    [
     [ 1, 2, 3 ],
     [ 4, 5, 6 ],
     [ 7, 8, 9 ]
    ]
    

    You should return [1,2,3,6,9,8,7,4,5].

    思路:创建函数互相递归调用,函数的参数要包括方向

    class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int>> &matrix) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            result.clear();
            if(matrix.empty()) return result;
            
            leftPos = 0; 
            rightPos = matrix[0].size()-1; 
            topPos = 0; 
            bottomPos = matrix.size()-1;
            goWider(matrix, true);
            return result;
        }
        void goWider(vector<vector<int>> &matrix, bool direct)
        {
            if(direct)
            {
                for(int i = leftPos; i<= rightPos; i++)
                {
                    result.push_back(matrix[topPos][i]);
                }
                topPos++;
                if(topPos > bottomPos) return;
                goDeeper(matrix, true);
            }
            else
            {
                for(int i = rightPos; i>= leftPos; i--)
                {
                    result.push_back(matrix[bottomPos][i]);
                }
                bottomPos--;
                if(topPos > bottomPos) return;
                goDeeper(matrix, false);
            }
        }
        void goDeeper(vector<vector<int>> &matrix, bool direct)
        {
            if(direct)
            {
                for(int i = topPos; i<= bottomPos; i++)
                {
                    result.push_back(matrix[i][rightPos]);
                }
                rightPos--;
                if(leftPos > rightPos) return;
                goWider(matrix, false);
            }
            else
            {
                for(int i = bottomPos; i>= topPos; i--)
                {
                    result.push_back(matrix[i][leftPos]);
                }
                leftPos++;
                if(leftPos > rightPos) return;
                goWider(matrix, true);
            }
        }
    private:
        vector<int> result;
        int leftPos;
        int rightPos;
        int topPos;
        int bottomPos;
    };
  • 相关阅读:
    训练1-J
    训练1-K
    训练1-P
    二分查找法详解
    POJ:1094-Sorting It All Out(拓扑排序经典题型)
    POJ:2632-Crashing Robots
    POJ:1086-Parencodings
    POJ:2586-Y2K Accounting Bug
    POJ:2109-Power of Cryptography(关于double的误差)
    POJ:1328-Radar Installation
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4854641.html
Copyright © 2020-2023  润新知