54. Spiral Matrix

来源:互联网 发布:网络即时通讯工具 编辑:程序博客网 时间:2024/05/18 09:35

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) {
        vector<int> v1;
        int m=matrix.size();
        if(m==0) return v1;
        int n=matrix[0].size();
        int la=0,lb=m,lc=0,ld=n;
        bool index=true;
        int i=0,j=0;
        while(1)
        {

            index=true;
            while((la<=i&&i<lb)&&j<ld)
            {
                v1.push_back(matrix[i][j++]);
                index=false;
            }
            i++;j--; ++la;
            while(i<lb &&(lc<=j&&j<ld) )
            {
                v1.push_back(matrix[i++][j]);
                index=false;
            }
            --i;--j; --ld;
            while(j>=lc && (la<=i&&i<lb))
            {
                v1.push_back(matrix[i][j--]);
                index=false;  
            }
            --i;++j;--lb;
            while(i>=la && (lc<=j&&j<ld))
            {
                v1.push_back(matrix[i--][j]);
                index=false;
            }
            ++lc;++i;++j;
            if(index) break;
        }
        return v1;
    }
};

0 0