給 m×n 矩陣,按順時針螺旋順序輸出所有元素。例如 [[1,2,3],[4,5,6],[7,8,9]] → [1,2,3,6,9,8,7,4,5]。
class Solution {
public:
vector spiralOrder(vector>& matrix) {
vector res;
if (matrix.empty()) return res;
int m = matrix.size(), n = matrix[0].size();
int top = 0, bottom = m-1, left = 0, right = n-1;
while (top <= bottom && left <= right) {
for (int j = left; j <= right; ++j) res.push_back(matrix[top][j]);
if (++top > bottom) break;
for (int i = top; i <= bottom; ++i) res.push_back(matrix[i][right]);
if (--right < left) break;
for (int j = right; j >= left; --j) res.push_back(matrix[bottom][j]);
if (--bottom < top) break;
for (int i = bottom; i >= top; --i) res.push_back(matrix[i][left]);
++left;
}
return res;
}
};
Spiral Matrix 是經典的矩陣遍歷題。**邊界收縮法** 代碼最簡潔、無額外空間、邏輯清晰,是面試首選寫法。DFS 法通用性強(適用於不規則螺旋),但常數較大。