給定 m x n 矩陣,按順時針螺旋順序返回所有元素。
範例:
輸入: [[1,2,3],
[4,5,6],
[7,8,9]]
輸出: [1,2,3,6,9,8,7,4,5]
維護四個邊界變數:
top、bottom:行邊界left、right:列邊界按順序遍歷:左→右(頂行)、上→下(右列)、右→左(底行)、下→上(左列),每完成一邊就收縮對應邊界,直到邊界交錯。
class Solution {
public:
vector spiralOrder(vector>& matrix) {
vector result;
if (matrix.empty()) return result;
int top = 0, bottom = matrix.size() - 1;
int left = 0, right = matrix[0].size() - 1;
while (true) {
// 左 → 右:頂行
for (int j = left; j <= right; ++j)
result.push_back(matrix[top][j]);
if (++top > bottom) break;
// 上 → 下:右列
for (int i = top; i <= bottom; ++i)
result.push_back(matrix[i][right]);
if (left > --right) break;
// 右 → 左:底行
for (int j = right; j >= left; --j)
result.push_back(matrix[bottom][j]);
if (top > --bottom) break;
// 下 → 上:左列
for (int i = bottom; i >= top; --i)
result.push_back(matrix[i][left]);
if (++left > right) break;
}
return result;
}
};
以 3×3 矩陣為例:
| 步驟 | 方向 | 邊界變化 | 輸出元素 |
|---|---|---|---|
| 1 | 左→右 | top: 0→1 | 1, 2, 3 |
| 2 | 上→下 | right: 2→1 | 6, 9 |
| 3 | 右→左 | bottom: 2→1 | 8, 7 |
| 4 | 下→上 | left: 0→1 | 4 |
| 5 | 左→右 | top: 1→2 (break) | 5 |
top > bottom 或 left > right