9 {
10 if (matrix.empty() || matrix[0].empty()) return {};
11
12 vector<int> answer;
13 answer.reserve((int)(matrix.size() * matrix[0].size()));
14 int m = (int)matrix.size(), n = (int)matrix[0].size();
15
16 int left = 0, right = n - 1, top = 0, bottom = m - 1;
17 while (left <= right && top <= bottom)
18 {
19 for (int j = left; j <= right; ++j)
20 answer.push_back(matrix[top][j]);
21 ++top;
22
23 for (int i = top; i <= bottom; ++i)
24 answer.push_back(matrix[i][right]);
25 --right;
26
27 if (top <= bottom)
28 {
29 for (int j = right; j >= left; --j)
30 answer.push_back(matrix[bottom][j]);
31 --bottom;
32 }
33
34 if (left <= right)
35 {
36 for (int i = bottom; i >= top; --i)
37 answer.push_back(matrix[i][left]);
38 ++left;
39 }
40 }
41
42 return answer;
43 }