**Input:** matrix = [[1,2,3],[4,5,6],[7,8,9]]
**Output:** [1,2,3,6,9,8,7,4,5]
**Input:** matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
**Output:** [1,2,3,4,8,12,11,10,9,5,6,7]
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<Integer>();
if (matrix.length == 0) return res;
int rb = 0, re = matrix.length-1;
int cb = 0, ce = matrix[0].length - 1;
while (rb <= re && cb <= ce) {
// special cases
if (rb == re){
for (int c = cb; c <= ce; c++) res.add(matrix[rb][c]);
break;
}
if (cb == ce) {
for (int r = rb; r <= re; r++) res.add(matrix[r][ce]);
break;
}
// top
for (int c = cb; c < ce; c++) res.add(matrix[rb][c]);
// right
for (int r = rb; r < re; r++) res.add(matrix[r][ce]);
// buttom
for (int c = ce; c > cb; c--) res.add(matrix[re][c]);
// left
for (int r = re; r > cb; r--) res.add(matrix[r][cb]);
// iterate
rb++;
re--;
cb++;
ce--;
}
return res;
}
}