leetcode_54. Spiral Matrix

版權聲明:本文爲博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/gxh27954/article/details/72454488

//https://leetcode.com/problems/spiral-matrix/#/description

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>();
        int size = matrix.size();
        int size2 = matrix[0].size();
        //cout<<size;
        //cout<<size2;
        int f[105][105];
        int v[10005];
        int i=0,j=-1;
        int count = 0;
        memset(f,0,sizeof(f));
        vector<int > ve;
        while(count<size*size2)
        {
            while(j+1<size2&&f[i][j+1]==0)
            {
                v[count++]=matrix[i][++j];
                f[i][j]=1;
            }
            while(i+1<size&&f[i+1][j]==0)
            {
                v[count++]=matrix[++i][j];
                f[i][j]=1;
            }
            while(j-1>=0&&f[i][j-1]==0)
            {
                v[count++]=matrix[i][--j];
                f[i][j]=1;
            }
            while(i-1>=0&&f[i-1][j]==0)
            {
                v[count++]=matrix[--i][j];
                f[i][j]=1;
            }
        }
        for(int i=0;i<size*size2;i++)
        {
            ve.push_back(v[i]);
        }
        return ve;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章