54. Spiral Matrix - Medium
前往題目
之前寫的文章
想法
- 初始的變數沒有想出來,有了
left right top
和bottom
就簡單了
思路
- 定義上下左右邊界,以下的
code
要注意out of boundary
- 先取
top elements
- 再取
right elements
- 注意
left
要小於right
,top
要小於bottom
以防special case
- 再取
bottom elements
- 再取
left elements
- 反覆直到全部都取到
Code
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList();
// Defining boundaries
int left = 0, right = matrix[0].length;
int top = 0, bottom = matrix.length;
while (left < right && top < bottom) {
// Get top row elements
for (int i = left; i < right; ++i) {
res.add(matrix[top][i]);
}
// Shrink the area
top += 1;
// Get the right col elements
for (int i = top; i < bottom; ++i) {
// Aware out of bound, so right - 1
res.add(matrix[i][right - 1]);
}
right -= 1;
// Check for special case
// Such as, [[1],[2],[3]]
if (!(left < right && top < bottom)) break;
// Get the bottom row elements
for (int i = right - 1; i > left - 1; --i) {
res.add(matrix[bottom - 1][i]);
}
bottom -= 1;
// Get the left col elements
for (int i = bottom - 1; i > top - 1 ; --i) {
res.add(matrix[i][left]);
}
left += 1;
}
return res;
}
}
54. Spiral Matrix - Medium
https://f88083.github.io/2024/03/10/54-Spiral-Matrix-Medium/