The logic is simple enough, but kind of ugly .....

```
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int i = 0, j = -1, r = 0, c = 1, d = 1, h = matrix.size()-1, w = (h >= 0 ? matrix[0].size() : 0), m = h, n = w;
vector<int> v;
while ((r && h > 0) || (c && w > 0)) {
v.push_back(matrix[i += r][j += c]);
if ((r && --m) || (c && --n)) continue;
if (r) m = --h;
else n = --w;
if (r = c) d = -d;
c += d;
}
return v;
}
};
```