class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int m = matrix.size(),n = matrix[0].size();
        vector<int> ans;
        //设定访问边界
        int up = 0,down = m -1,left = 0,right = n -1;
        while(true)
        {
            //从左向右访问
            for(int i = left;i <= right;i++) 
                ans.push_back(matrix[up][i]);
            if(++up > down) break;
            
            //从上向下访问
            for(int i = up;i <= down;i++) ans.push_back(matrix[i][right]);
            if(--right < left) break;
            
            //从右向左访问
            for(int i = right;i >= left;i--) ans.push_back(matrix[down][i]);
            if(--down < up) break;
            
            //从下向上访问
            for(int i = down;i >= up;i--)  ans.push_back(matrix[i][left]);
            if(++left > right) break;
        }
        
        return ans;
    }
};

运行结果:

Runtime: 0 ms, faster than 100.00% of C++ online submissions for Spiral Matrix.
Memory Usage: 6.9 MB, less than 50.09% of C++ online submissions for Spiral Matrix.