思路:
遍历的过程中处理好上、下、左、右的边界,别越界即可。
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new LinkedList<>();
int top = 0;
int bottom = matrix.length - 1;
int left = 0;
int right = matrix[0].length - 1;
while(true){
for(int i = left; i <= right;i++){
res.add(matrix[top][i]);
}
if(++top > bottom) break;
for(int i = top; i <= bottom; i++){
res.add(matrix[i][right]);
}
if(left > --right) break;
for(int i = right; i >= left; i--){
res.add(matrix[bottom][i]);
}
if(top > --bottom) break;
for(int i = bottom; i >= top; i--){
res.add(matrix[i][left]);
}
if(++left > right) break;
}
return res;
}
}