Spiral Matrix

LeetCode #54


Description:

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example:

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

Idea:

设个beginX, endX, beginY, endY. 并且用这些来检查是否停止。

Code:

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> result;
        if(matrix.empty()) return result;
        int m=matrix.size();
        int n=matrix[0].size();
        int beginX=0, endX=n-1;
        int beginY=0, endY=m-1;
        while(true){
            for(int i=beginX; i<=endX; ++i){
                result.push_back(matrix[beginY][i]);
            }
            if(++beginY>endY) break;
            for(int j=beginY; j<=endY; ++j){
                result.push_back(matrix[j][endX]);
            }
            if(--endX<beginX) break;
            for(int i=endX; i>=beginX; --i){
                result.push_back(matrix[endY][i]);
            }
            if(--endY<beginY) break;
            for(int j=endY; j>=beginY; --j){
                result.push_back(matrix[j][beginX]);
            }
            if(++beginX>endX) break;
        }

        return result;
    }
};

results matching ""

    No results matching ""