classSolution { public: vector<int> spiralOrder(vector<vector<int>>& matrix){ vector<int> result; int m = matrix.size(); if (m == 0) return result; int n = matrix[0].size(); int up = 0, down = m - 1, left = 0, right = n - 1;
while (true) { // 上方,从左到右 for (int col = left; col <= right; col++) result.emplace_back(matrix[up][col]); if (++up > down) break;
// 右方,从上到下 for (int row = up; row <= down; row++) result.emplace_back(matrix[row][right]); if (--right < left) break;
// 下方,从右到左 for (int col = right; col >= left; col--) result.emplace_back(matrix[down][col]); if (--down < up) break;