- class Solution {
- //key observe: when any component is done, its beginX,endX or beginY,endX will change
- public:
- vector<int> spiralOrder(vector<vector<int> >& matrix) {
- vector<int> result;
- if (matrix.empty()) return result;
- int beginX = 0, endX = matrix[0].size() - 1;
- int beginY = 0, endY = matrix.size() - 1;
- while (true) {
- // From left to right
- for (int i = beginX; i <= endX; ++i)
- result.push_back(matrix[beginY][i]);
- if (++beginY > endY) break;
- // From top down
- for (int i = beginY; i <= endY; ++i)
- result.push_back(matrix[i][endX]);
- if (beginX > --endX) break;
- // From right to left
- for (int i = endX; i >= beginX; --i)
- result.push_back(matrix[endY][i]);
- if (beginY > --endY) break;
- // From bottom up
- for (int i = endY; i >= beginY; --i)
- result.push_back(matrix[i][beginX]);
- if (++beginX > endX) break;
- }
- return result;
- }
- };
Tuesday, June 17, 2014
Spiral Matrix -- Leetcode
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment