java
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
int m = matrix.length, n = matrix[0].length;
int leftUpM = 0, leftUpN = 0, rightDownM = m - 1, rightDownN = n - 1;
List<Integer> res = new ArrayList<>();
while (leftUpM <= rightDownM && leftUpN <= rightDownN) {
for (int i = leftUpN; i <= rightDownN; ++i) { // 向右
res.add(matrix[leftUpM][i]);
}
for (int i = leftUpM + 1; i < rightDownM; ++i) { // 向下
res.add(matrix[i][rightDownN]);
}
for (int i = rightDownN; i >= leftUpN && leftUpM < rightDownM; --i) { // 向左
res.add(matrix[rightDownM][i]);
}
for (int i = rightDownM - 1; i > leftUpM && leftUpN < rightDownN; --i) { // 向上
res.add(matrix[i][leftUpN]);
}
++leftUpM;
++leftUpN;
--rightDownM;
--rightDownN;
}
return res;
}
}