```
vector<int> spiralOrder(vector<vector<int> > &matrix) {
vector <int> res;
if (matrix.empty()) return res;
int m = matrix.size();
int n = matrix[0].size();
int col_st = 0, col_ed = n-1,row_st = 0, row_ed = m-1;
while (true)
{
for (int i=col_st;i<=col_ed;i++) res.push_back(matrix[row_st][i]);
row_st++;
if(row_st>row_ed || col_st>col_ed) break;
for (int j=row_st;j<=row_ed;j++) res.push_back(matrix[j][col_ed]);
col_ed--;
if(row_st>row_ed || col_st>col_ed) break;
for (int i=col_ed;i>=col_st;i--) res.push_back(matrix[row_ed][i]);
row_ed--;
if(row_st>row_ed || col_st>col_ed) break;
for (int j=row_ed;j>=row_st;j--) res.push_back(matrix[j][col_st]);
col_st++;
if(row_st>row_ed ||col_st>col_ed) break;
}
return res;
}
```