Simple C++ solution based on direction


  • 0
    L

    Just mimic the natural instinct.

    class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int>>& matrix) {
          vector<int> res;
          
          if (matrix.empty()) return res;
          
          vector<vector<int>> dirs = {{0,1}, {1,0}, {0,-1},{-1,0}};
          
          vector<int> steps = {matrix[0].size(), matrix.size()-1};
          
          int i=0;
          int n = 0;
          int x=0, y=-1;
          while ( n=steps[i%2])
          {
              while (n-->0)
              {
                  x+=dirs[i][0];
                  y+=dirs[i][1];
                  res.push_back(matrix[x][y]);
              }
              
              steps[i%2]--;
              i = (i+1)%4;
          }
          
          return res;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.