class Solution {
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        vector<int> res;
        if(matrix.size() == 0)
            return res;
        int m = matrix.size();
        int n = matrix[0].size();
        int start_x = 0;
        int start_y = 0;
        int loop = max(m/2,n/2);
        int offset = 1;
        while(loop--)
        {
            int i = start_x,j = start_y;
            for(;j< n - offset && res.size() < m*n;++j)
                res.push_back(matrix[i][j]);
            for(;i < m - offset && res.size() < m*n;++i)
                res.push_back(matrix[i][j]);
            for(;j>start_y && res.size() < m*n;--j)
                res.push_back(matrix[i][j]);
            for(;i>start_x && res.size() < m*n;--i)
                res.push_back(matrix[i][j]);
            if(res.size() == m*n)
                break;
            offset++;
            start_x++;
            start_y++;
        }
        if( m == n && m % 2 == 1)
            res.push_back(matrix[m/2][n/2]);
        return res;
    }
};