LeetCode 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) {

        vector<int> ans;
        if(matrix.size() == 0)
            return ans;

        int x = 0, y = 0;
        int row = matrix.size(), col = matrix[0].size();
        while(true)
        {
            for(int i=y; i<col-y; ++ i)
                ans.push_back(matrix[x][i]);
            if(x * 2 + 1 >= row)
                break;
            for(int i=x+1; i<row-x; ++ i)
                ans.push_back(matrix[i][col-y-1]);
            if(y * 2 + 1 >= col)
                break;
            for(int i=col-y-2; i>=y; -- i)
                ans.push_back(matrix[row-x-1][i]);
            if(x * 2 + 2 >= row)
                break;
            for(int i=row-x-2; i>x; -- i)
                ans.push_back(matrix[i][y]);
            if(y * 2 + 2 >= col)
                break;
            x ++, y ++;
        }
        return ans;
    }
};
posted @ 2017-04-05 11:35  aiterator  阅读(93)  评论(0编辑  收藏  举报