#include <vector>
class Solution {
public:
    int m;
    int n;
    vector<int> ans;
    vector<vector<int> > matrix;
    void myPrint(int x1,int y1,int x2,int y2){
        for(int i=y1;i<=y2;i++) ans.push_back(matrix[x1][i]);
        for(int i=x1+1;i<=x2;i++) ans.push_back(matrix[i][y2]);
        for(int i=y2-1;i>=y1;i--) ans.push_back(matrix[x2][i]);
        for(int i=x2-1;i>x1;i--) ans.push_back(matrix[i][y1]);
    }
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        if(matrix.size()==0) return ans;
        m=matrix.size();
        n=matrix[0].size();
        this->matrix=matrix;
        int x1=0,y1=0,x2=m-1,y2=n-1;
        while(x2>x1&&y2>y1){
            myPrint(x1,y1,x2,y2);
            x1++;
            y1++;
            x2--;
            y2--;    
        }
        if(x1==x2) {
            for(int i=y1;i<=y2;i++) ans.push_back(matrix[x1][i]);
        }
        else if(y1==y2) {
            for(int i=x1;i<=x2;i++) ans.push_back(matrix[i][y1]);
        }
        return ans;
    }
};