Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- vector<int> spiralOrder(vector<vector<int>>& matrix) {
- vector<int> ans;
- if (matrix.empty())
- {
- return ans;
- }
- int m = matrix.size(), n = matrix[0].size();
- int top = 0, down = m - 1, left = 0, right = n - 1;
- while (true) {
- for (int j = left; j <= right; j++)
- {
- ans.push_back(matrix[top][j]);
- }
- if (++top > down)
- {
- break;
- }
- for (int i = top; i <= down; i++)
- {
- ans.push_back(matrix[i][right]);
- }
- if (--right < left)
- {
- break;
- }
- for (int j = right; j >= left; j--)
- {
- ans.push_back(matrix[down][j]);
- }
- if (--down < top)
- {
- break;
- }
- for (int i = down; i >= top; i--)
- {
- ans.push_back(matrix[i][left]);
- }
- if (++left > right)
- {
- break;
- }
- }
- return ans;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment