zoukankan      html  css  js  c++  java
  • 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;
    };
  • 相关阅读:
    Git

    学而不记则徒劳无功
    Redis基础
    哈希表
    第一个Python程序
    Python 环境搭建 基于 Windows
    执行数据库的插入操作 insert
    Eclipse连接到My sql数据库的操作总结/配置数据库驱动
    数据库 (一)
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4854641.html
Copyright © 2011-2022 走看看