class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list = new ArrayList<>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return list;
}
int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
// Traverse from left to right
for (int i = left; i <= right; i++) {
list.add(matrix[top][i]);
}
top++;
// Traverse from top to bottom
for (int i = top; i <= bottom; i++) {
list.add(matrix[i][right]);
}
right--;
// Traverse from right to left
if (top <= bottom) {
for (int i = right; i >= left; i--) {
list.add(matrix[bottom][i]);
}
bottom--;
}
// Traverse from bottom to top
if (left <= right) {
for (int i = bottom; i >= top; i--) {
list.add(matrix[i][left]);
}
left++;
}
}
return list;
}
}
标签:matrix,螺旋,54,top,bottom,list,length,矩阵,left
From: https://www.cnblogs.com/chenyi502/p/17629919.html