Advertisement
Guest User

Untitled

a guest
Jan 21st, 2020
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.18 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<pair<int, int>> moves {
  4.         {  0, +1 }, // right
  5.         { +1,  0 }, // down
  6.         {  0, -1 }, // left
  7.         { -1,  0 }, // up
  8.     };
  9.     vector<vector<bool>> visited;
  10.  
  11.     bool valid(int x, int y)
  12.     {
  13.         return 0 <= x && x < visited.size() &&
  14.                0 <= y && y < visited[0].size();
  15.     }
  16.  
  17.     void walk(int x, int y, vector<vector<int>>& matrix, vector<int>& ans, int direction = 0)
  18.     {
  19.         visited[x][y] = true;
  20.         ans.push_back(matrix[x][y]);
  21.         int n = moves.size();
  22.         for (int i = 0; i < n; ++i)
  23.         {
  24.             int dx, dy, nextDirection = (direction + i) % n;
  25.             tie(dx, dy) = moves[nextDirection];
  26.             if (!valid(x + dx, y + dy) || visited[x + dx][y + dy])
  27.             {
  28.                 continue;
  29.             }
  30.             walk(x + dx, y + dy, matrix, ans, nextDirection);
  31.         }
  32.     }
  33.  
  34.     vector<int> spiralOrder(vector<vector<int>>& matrix) {
  35.         if (matrix.empty()) { return {}; }
  36.  
  37.         vector<int> ans;
  38.         visited.resize(matrix.size(), vector<bool>(matrix[0].size(), false));
  39.         walk(0, 0, matrix, ans);
  40.         return ans;
  41.     }
  42. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement