官解
官方题目
=========================================================================
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
1、数组为空返回空
2、闭区间上下左右界限
3、循环,每次循环一圈
4、遍历顺序 → ↓ ← ↑ 加入到结果数组
5、注意:
如果存在相等情况只需要前两步即可,
left和right是指的第二个坐标,top和bottom是第一个坐标。
每行遍历要注意除了→以外从第二个开始遍历,↑最后一个不能遍历
class Solution {
public List spiralOrder(int[][] matrix) {
List order = new ArrayList();
// 数组为空返回空
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;
}
}



