classSolution { public: vector<int> spiralOrder(vector<vector<int>>& matrix){ int n = matrix.size(); int m = matrix[0].size(); vector<int> ans;
int x1 = 0 , y1 = 0; int x2 = n - 1, y2 = m - 1; while(true) { if(x1 > x2 || y1 > y2) { break; }
if(x1 == x2) { for(int i = y1 ; i <= y2 ; i++)ans.push_back(matrix[x1][i]); break; }
if(y1 == y2) { for(int i = x1 ; i <= x2 ; i++)ans.push_back(matrix[i][y1]); break; }
for(int i = y1 ; i < y2 ; i++)ans.push_back(matrix[x1][i]); for(int i = x1 ; i < x2 ; i++)ans.push_back(matrix[i][y2]); for(int i = y2 ; i > y1 ; i--)ans.push_back(matrix[x2][i]); for(int i = x2 ; i > x1 ; i--)ans.push_back(matrix[i][y1]);