class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> ans = new ArrayList<>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return ans;
}
int rows = matrix.length;
int cols = matrix[0].length;
int left = 0, right = cols – 1;
int top = 0, bottom = rows – 1;
while (left <= right && top <= bottom) {
for (int i = left; i <= right; i++) {
ans.add(matrix[top][i]);
}
top++;
for (int i = top; i <= bottom; i++) {
ans.add(matrix[i][right]);
}
right–;
if (top <= bottom) {
for (int i = right; i >= left; i–) {
ans.add(matrix[bottom][i]);
}
bottom–;
}
if (left <= right) {
for (int i = bottom; i >= top; i–) {
ans.add(matrix[i][left]);
}
left++;
}
}
return ans;
}
}
这是我的一个思路,主循环终止条件用 left <= right && top <= bottom,
两条反向边必须加二次判断:
遍历底边前加 if (top <= bottom),防止只剩单行时重复遍历
遍历左边前加 if (left <= right),防止只剩单列时重复遍历
固定遍历顺序:上边从左到右 → 右边从上到下 → 下边从右到左 → 左边从下到上,每走完一条边立刻收缩对应边界。因为边界边遍历边收缩,所以要 if (left <= right)if (top <= bottom)必须要包含进行两次筛选。
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> order = new ArrayList<Integer>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return order;
}
int rows = matrix.length, columns = matrix[0].length;
int left = 0, right = columns – 1, top = 0, bottom = rows – 1;
while (left <= right && top <= bottom) {
for (int column = left; column <= right; column++) {
order.add(matrix[top][column]);
}
for (int row = top + 1; row <= bottom; row++) {
order.add(matrix[row][right]);
}
if (left < right && top < bottom) {
for (int column = right – 1; column > left; column–) {
order.add(matrix[bottom][column]);
}
for (int row = bottom; row > top; row–) {
order.add(matrix[row][left]);
}
}
left++;
right–;
top++;
bottom–;
}
return order;
}
}
官方版本写的比较巧妙一点,每次遍历边界不变靠top+1,right-1进行跳过重复,每一层循环之后收缩边界




