class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
int n = matrix.size();
if (!n) return res;
int m = matrix[0].size();
if (!m) return res;
vector<vector<bool>> st(n, vector<bool> (m));
// int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1}; //按照这个方向是错的
int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0}; //这个方向是唯一的
for (int i = 0, x = 0, y = 0, d = 0; i < n * m; i ++) {
res.push_back(matrix[x][y]);
st[x][y] = true;
int a = x + dx[d];
int b = y + dy[d];
if (a < 0 || a >= n || b < 0 || b >= m || st[a][b]) {
d = (d + 1) % 4;
a = x + dx[d], b = y + dy[d];
}
x = a, y = b;
}
return res;
}
};