class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return res;
}
int rows = matrix.length;
int cols = matrix[0].length;
int left = 0, right = cols - 1;
int top = 0, bottom = rows - 1;
// right --> bottom --> left --> top
while (top <= bottom && left <= right) {
// right
for (int i = left; i <= right; i++) {
res.add(matrix[top][i]);
}
top++;
// --> bottom
for (int i = top; i <= bottom; i++) {
res.add(matrix[i][right]);
}
right--;
// --> left
if (top <= bottom) {
for (int i = right; i >= left; i--) {
res.add(matrix[bottom][i]);
}
bottom--;
}
// --> top
if (left <= right) {
for (int i = bottom; i >= top; i--) {
res.add(matrix[i][left]);
}
left++;
}
}
return res;
}
}
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Top comments (0)