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;
}
}