c++ solution (0 ms)


  • 0
    class Solution {
    public:
      vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int n = matrix.size();
        vector<int> ans;
        if (n == 0) return ans;
        int m = matrix[0].size();
        int top = 0, right = m - 1, bot = n - 1, left = 0;
        while (true) {
          for (int i = left; i <= right; ++i) ans.push_back(matrix[top][i]);
          top++; 
          if (top > bot) break;
          for (int i = top; i <= bot; ++i) ans.push_back(matrix[i][right]);
          right--; 
          if (left > right) break;
          for (int i = right; i >= left; --i) ans.push_back(matrix[bot][i]);
          bot--; 
          if (top > bot) break;
          for (int i = bot; i >= top; --i) ans.push_back(matrix[i][left]);
          left++; 
          if (left > right) break;
        }
        return ans;
      }
    };
    

Log in to reply
 

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