class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
int num, n = 0;
int i = 0, j = 0;
int left = 0, right = matrix[0].size(), up = 1, down = matrix.size();
num = matrix.size() * matrix[0].size();
while (n < num) {
while (j < right) {
res.push_back(matrix[i][j]);
j ;
n ;
}
if (n >= num) return res;
right--;
j--;
i ;
while (i < down) {
res.push_back(matrix[i][j]);
i ;
n ;
}
if (n >= num) return res;
down--;
i--;
j--;
while (j >= left) {
res.push_back(matrix[i][j]);
j--;
n ;
}
if (n >= num) return res;
left ;
j ;
i--;
while (i >= up) {
res.push_back(matrix[i][j]);
i--;
n ;
}
if (n >= num) return res;
up ;
i ;
j ;
}
return res;
}
};