
java
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
if(matrix == null || matrix.length == 0){
return null;
}
//四个边界
int top = 0;
int bottom = matrix.length - 1;
int left = 0;
int right = matrix[0].length - 1;
while(top <= bottom && left <= right){
for(int i = left; i <=right; i++){
result.add(matrix[top][i]);
}
top++;
for(int i = top; i <= bottom; i++){
result.add(matrix[i][right]);
}
right--;
//额外进行一次判断
if(top <= bottom && left <= right){
for(int i = right; i >= left; i--){
result.add(matrix[bottom][i]);
}
bottom--;
for(int i = bottom; i >= top; i--){
result.add(matrix[i][left]);
}
left++;
}
}
return result;
}
}
这里需要注意第二个判断,防止读取重复数据。