leetcode Spiral Matrix 螺旋输出矩阵

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].
思路:
来看第一圈,行左到右->列上到下->行右到左->列下到上,
后面一直重复,来四个游标定边界,left,right,up,down
while终止条件:left>right || up>down

#include
#include
using namespace std;
vector<int> spiral(vector<vector<int>>& matrix)
{
    int left=0;
    int right=matrix[0].size()-1;
    int up=0;
    int down=matrix.size()-1;
    vector<int> v;
    while(left<=right && up<=down)
    {
        //从左到右遍历一行
        for(int i=left;i<=right;i++)
        {
            v.push_back(matrix[up][i]);
        }
        up++;//行下移
        //从上往下遍历一列
        for(int j=up;j<=down;j++)
        {
            v.push_back(matrix[j][right]);
        }
        right--;//列左移
        //从右向左遍历一行
        if(up//避免行重复
        {
            for(int p=right;p>=left;p--)
            {
                v.push_back(matrix[down][p]);
            }
        }
        down--;//行上移
        //从下往上遍历一列
        if(left//避免列重复
        {
            for(int q=down;q>=up;q--)
            {
                v.push_back(matrix[q][left]);
            }
        }
        left++;//列右移
    }
    return v;
}

int main()
{
    vector<vector<int>> v1={{1,2,3},{4,5,6},{7,8,9}};
    vector<int> v2=spiral(v1);
    for(auto iter:v2)
    {
        cout<" ";
    }
}

你可能感兴趣的:(数组)