//行列数 int m = matrix.size(); int n = matrix[0].size();
//上下左右标记 int top = 0; int down = m - 1; int left = -1; int right = n - 1;
int num = 0; //记录标号 vector<int> ans(m * n); //存储结果,为了提速,先分配大小为m*n
//循环赋值 while (num < m * n) { if (++left > right) break; for (int i = left; i <= right; ++i) ans[num++] = matrix[top][i]; if (++top > down) break; for (int i = top; i <= down; ++i) ans[num++] = matrix[i][right]; if (--right < left) break; for (int i = right; i >= left; --i) ans[num++] = matrix[down][i]; if (--down < top) break; for (int i = down; i >= top; --i) ans[num++] = matrix[i][left]; }