class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
if (matrix == null || matrix.length == 0) return new ArrayList<>();
int left = 0, right = matrix[0].length - 1;
int top = 0, bottom = matrix.length - 1;
List<Integer> ret = new ArrayList<>();
while (left <= right && top <= bottom) {
for (int i = left; i <= right; ++i) ret.add(matrix[top][i]);
for (int i = ++top; i <= bottom; ++i) ret.add(matrix[i][right]);
// bug - 1 => avoid duplicates collected;
if (top > bottom) break;
for (int i = --right; i >= left; --i) ret.add(matrix[bottom][i]);
if (left > right) break;
for (int i = --bottom; i >= top; --i) ret.add(matrix[i][left]);
left++;
}
return ret;
}
54. 螺旋矩阵
最新推荐文章于 2024-02-08 16:23:13 发布