[leetcode]Spiral Matrix

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        vector<int> ans;
        int m = matrix.size();
        if(m == 0) return ans;
        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++)
                ans.push_back(matrix[beginY][i]);
            beginY++;
            if(beginY > endY) break;
            for(int i = beginY ; i <= endY ; i++)
                ans.push_back(matrix[i][endX]);
            endX--;
            if(beginX > endX) break;
            for(int i = endX ; i >= beginX ; i--)
                ans.push_back(matrix[endY][i]);
            endY--;
            if(beginY > endY) break;
            for(int i = endY ; i >= beginY ; i--)
                ans.push_back(matrix[i][beginX]);
            beginX++;
            if(beginX > endX) break;
        }
        return ans;
    }
};

 

你可能感兴趣的:(LeetCode)