LeetCode | 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].

思路:

利用递归的方法,共有如下的两种情况:第一种情况先遍历右上侧面再遍历左下的方形部分;第二种情况先遍历左下侧面再遍历右上的方形部分。侧面与方形部分可以用起始,终止坐标表示。
《LeetCode | Spiral Matrix》

代码:

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        if(matrix.size()==0||matrix[0].size()==0)
        {
            return *(new vector<int>());
        }
        int x1=0;
        int y1=0;
        int y2=matrix.size()-1;
        int x2=matrix[0].size()-1;

        return getOutside(true, x1, y1, x2, y2, matrix);
    }
    
    vector<int> getOutside(bool upside, int x1, int y1, int x2, int y2,vector<vector<int> > &matrix)
    {
        vector<int> r;
        if(x1 == x2 && y1 == y2)
        {
            r.push_back(matrix[y1][x1]);
        }
        else
        {
            if(upside)
            {
                for(int i=x1;i<=x2;i++)
                {
                    r.push_back(matrix[y1][i]);
                }
                if(y2>y1)
                {
                    for(int i=y1+1;i<=y2;i++)
                    {
                        r.push_back(matrix[i][x2]);
                    }
                }
                int x3 = x2-1;
                int y3 = y2;
                int x4 = x1;
                int y4 = y1+1;
                if(x3>=x4 && y3>=y4)
                {
                    vector<int> tmp = getOutside(!upside, x3, y3, x4, y4,matrix);
                    for(int k=0;k<tmp.size();k++)
                    {
                        r.push_back(tmp[k]);
                    }
                }
            }
            else
            {
                for(int i=x1;i>=x2;i--)
                {
                    r.push_back(matrix[y1][i]);
                }
                if(y1>y2)
                {
                    for(int i=y1-1;i>=y2;i--)
                    {
                        r.push_back(matrix[i][x2]);
                    }
                }
                int x3 = x2+1;
                int y3 = y2;
                int x4 = x1;
                int y4 = y1-1;
                if(x3<=x4 && y3<=y4)
                {
                    vector<int> tmp = getOutside(!upside, x3, y3, x4, y4,matrix);
                    for(int k=0;k<tmp.size();k++)
                    {
                        r.push_back(tmp[k]);
                    }
                }
            }
        }
        return r;
    }
};

    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/17528505
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞