思路:
这道题主要是对空间上有所思考,每次转一圈上右下左各减少一层。不妨设top,right,down,left,每次旋转一圈 top++,right--,down--,left++
代码如下:
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
if (matrix==null||matrix.length==0||matrix[0].length==0){
return new ArrayList<>();
}
int m=matrix.length;
int n=matrix[0].length;
List<Integer> list=new ArrayList<>();
int total=m*n;
int left=0;int right=n-1;int top=0;int down=m-1;
while (list.size()<total) {
//从左向右运动
for (int col = left; col <= right && list.size() < total; col++) {
list.add(matrix[top][col]);
}
//上边界下移
top++;
//从上往下运动
for (int row = top; row <= down && list.size() < total; row++) {
list.add(matrix[row][right]);
}
//有边界左移
right--;
//从右往左运动
for (int col = right; col >= left && list.size() < total; col--) {
list.add(matrix[down][col]);
}
//下边界上移
down--;
//从下往上
for (int row = down; row >= top && list.size() < total; row--) {
list.add(matrix[row][left]);
}
left++;
}
return list;
}
}