原题链接:https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/
1、方法一
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int n = matrix.size();
if (n == 0) return {};
int m = matrix[0].size();
vector<int> ans;
int up = 0, down = n - 1, left = 0, right = m - 1, count = 0;
while (true) {
for (int i = left; i <= right; i++) ans.push_back(matrix[up][i]);
if (++up > down) break;
for (int i = up; i <= down; i++) ans.push_back(matrix[i][right]);
if (--right < left) break;
for (int i = right; i >= left; i--) ans.push_back(matrix[down][i]);
if (--down < up) break;
for (int i = down; i >= up; i--) ans.push_back(matrix[i][left]);
if (++left > right) break;
}
return ans;
}
2、方法二
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if (matrix.empty()) return res;
int n = matrix.size(), m = matrix[0].size();
vector<vector<bool>> st(n ,vector<bool>(m, false));
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
int x = 0, y = 0, d = 1;
for (int k = 0; k < n * m; k ++ ) {
res.push_back(matrix[x][y]);
st[x][y] = true;
int a = x + dx[d], 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;
}