官解
采用四个变量分别记录上下左右
然后根据循环方向分别移动一格,然后判断是否需要退出循环。
java
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 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(--right < left) break;
// 右到左
for(int i = right; i>=left;i--) res.add(matrix[bottom][i]);
// 上
if(--bottom < top) break;
// 下到上
for(int i = bottom; i>=top;i--) res.add(matrix[i][left]);
// 右
if(++left > right) break;
}
return res;
}
}