54. Spiral Matrix

Posted 为了更优秀的你,加油!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        if(matrix.empty())return {};
        vector<int>res;
        int n = matrix.size(), m = matrix[0].size();
        int left = 0, right = m-1, up = 0, down = n-1;
        int index=0;
        while(left < right && up < down){
            for(int i = left; i < right; i++)
                res.push_back(matrix[up][i]);
            for(int i = up; i < down; i++)
                res.push_back(matrix[i][right]);
            for(int i = right; i > left; i--){
                res.push_back(matrix[down][i]);
            }
            for(int i = down; i > up; i--){
                res.push_back(matrix[i][left]);
            }
            left++;right--;up++;down--;
        }
      //  cout<<left<<‘ ‘<<right<<‘ ‘<<up<<‘ ‘<<down<<endl;
        if(left == right)
            for(int i = up; i <= down; i++)res.push_back(matrix[i][left]);
        else if(up == down)
            for(int i = left; i <= right; i++)res.push_back(matrix[up][i]);
        return res;
    }
};

 

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

Leetcode 54. Spiral Matrix

54. Spiral Matrix && 59. Spiral Matrix II

#Leetcode# 54. Spiral Matrix

54. Spiral Matrix

54. Spiral Matrix

LeetCode 54. Spiral Matrix