思路: flag数组标记 + rows*cols终止
同类题:leetcode59. 螺旋矩阵 II(中等)
https://blog.csdn.net/zhangjiaji111/article/details/125586693
class Solution {
public:
int xy[4][2] = {0, 1, 1, 0, 0, -1, -1, 0};
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int n = matrix.size(), m = matrix[0].size();
vector<int> ans;
vector<vector<int>> flag(n, vector<int>(m));
int x = 0, y = 0, index = 0;
for (int i = 0; i < n * m; ++i) {
ans.push_back(matrix[x][y]);
flag[x][y] = 1;
int newx = x + xy[index][0], newy = y + xy[index][1];
if (newx < 0 || newx >= n || newy < 0 || newy >= m || flag[newx][newy]) {
index = (index + 1) % 4;
}
x = x + xy[index][0];
y = y + xy[index][1];
}
return ans;
}
};