class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int> res; int top = 0, bot = matrix.size() - 1; int left = 0, right = matrix[0].size() - 1; while (left <= right && top <= bot) { // → traverse top row left to right for (int c = left; c <= right; c++) res.push_back(matrix[top][c]); top++; // ↓ traverse right column top to bottom for (int r = top; r <= bot; r++) res.push_back(matrix[r][right]); right--; // ← traverse bottom row right to left if (top <= bot) { for (int c = right; c >= left; c--) res.push_back(matrix[bot][c]); bot--; } // ↑ traverse left column bottom to top if (left <= right) { for (int r = bot; r >= top; r--) res.push_back(matrix[r][left]); left++; } } return res; } };