zoukankan      html  css  js  c++  java
  • leetcode[54]Spiral Matrix

    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:
    void  solve(vector<vector<int>> &matrix, vector<int> &res, int left, int right, int up, int down)
    {
        if (up>down||left>right)
            return;
        if (up==down)
        {
            for (int j=left;j<=right;j++)
            {
               res.push_back(matrix[up][j]);
            }
            return;
        }
        if (left==right)
        {
            for (int i=up;i<=down;i++)
            {
                res.push_back(matrix[i][left]);
            }
            return;
        }
        for (int j=left;j<right;j++)
            res.push_back(matrix[up][j]);
        for (int i=up;i<down;i++)
            res.push_back(matrix[i][right]);
        for (int j=right;j>left;j--)
            res.push_back(matrix[down][j]);
        for(int i=down;i>up;i--)
            res.push_back(matrix[i][left]);
        solve(matrix, res, left+1, right-1, up+1, down-1);
    }
    vector<int> spiralOrder(vector<vector<int> > &matrix) 
    {
        vector<int> res;
        if(matrix.empty())return res;
        solve(matrix,res,0,matrix[0].size()-1,0,matrix.size()-1);
        return res;
    }
    };
  • 相关阅读:
    2021.4.2 Python基础及介绍
    2021.4.1 团队组队
    冲击信号
    信号卷积(线性卷积)
    数字图像处理基本概念
    计算机视觉发展及主要研究方向
    SVM 之 SMO 算法
    FP Growth 算法
    Apriori 算法
    26 实战页式内存管理 下
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4281543.html
Copyright © 2011-2022 走看看