题解一:
模拟:定义四个边界,指针按右下左上的顺序遍历,每遍历一条边,边界就减一,并且在某个方向没有可以遍历的数时直接返回。
import java.util.ArrayList;
import java.util.List;
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list = new ArrayList<>();
int down = matrix.length - 1;//下边界
int right = matrix[0].length - 1;//右边界
int up = 0;//上边界
int left = 0;//左边界
boolean flag;
while (true) {
flag = false;
for (int i = up, j = left; j <= right; j++) {//向右
list.add(matrix[i][j]);
flag = true;
}
if (!flag) return list;
up++;
flag = false;
for (int i = up, j = right; i <= down; i++) {//向下
list.add(matrix[i][j]);
flag = true;
}
if (!flag) return list;
right--;
flag = false;
for (int i = down, j = right; j >= left; j--) {//向左
list.add(matrix[i][j]);
flag = true;
}
if (!flag) return list;
down--;
flag = false;
for (int i = down, j = left; i >= up; i--) {//向上
list.add(matrix[i][j]);
flag = true;
}
if (!flag) return list;
left++;
}
}
}