jayati

Spiral Matrix

Jan 28th, 2023
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.34 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<int> spiralOrder(vector<vector<int>>& matrix) {
  4.          vector<int> ans;
  5.         if (matrix.empty())
  6.         {
  7.              return ans;
  8.         }
  9.             int m = matrix.size(), n = matrix[0].size();
  10.             int top = 0, down = m - 1, left = 0, right = n - 1;
  11.             while (true) {
  12.                 for (int j = left; j <= right; j++)
  13.                 {
  14.                    ans.push_back(matrix[top][j]);
  15.                 }
  16.                 if (++top > down)
  17.                 {
  18.                    break;
  19.                 }
  20.                 for (int i = top; i <= down; i++)
  21.                 {
  22.                   ans.push_back(matrix[i][right]);
  23.                 }
  24.                 if (--right < left)
  25.                 {
  26.                   break;
  27.                 }
  28.                 for (int j = right; j >= left; j--)
  29.                 {
  30.                  ans.push_back(matrix[down][j]);
  31.                 }
  32.                
  33.                 if (--down < top)
  34.                 {
  35.                   break;
  36.                 }
  37.                 for (int i = down; i >= top; i--)
  38.                 {
  39.                   ans.push_back(matrix[i][left]);
  40.                 }
  41.                 if (++left > right)
  42.                 {
  43.                  break;
  44.                 }
  45.     }
  46.     return ans;
  47.        
  48.     }
  49. };
Advertisement
Add Comment
Please, Sign In to add comment