Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

1
2
3
4
5
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new LinkedList<>();
if (matrix == null || matrix.length == 0) return res;
int rowEnd = matrix.length - 1, columnEnd = matrix[0].length - 1, rowBegin = 0, columnBegin = 0;

while (rowBegin <= rowEnd && columnBegin <= columnEnd) {
// top, left to right
for (int i = columnBegin; i <= columnEnd; i++) {
res.add(matrix[rowBegin][i]);
}
rowBegin++;
// right, top to bottom
for (int j = rowBegin; j <= rowEnd; j++) {
res.add(matrix[j][columnEnd]);
}
columnEnd--;
// bottom, right to left
if (rowBegin <= rowEnd) {
for (int k = columnEnd; k >= columnBegin; k--) {
res.add(matrix[rowEnd][k]);
}
}

// left, bottom to top
rowEnd--;
if (columnBegin <= columnEnd) {
for (int l = rowEnd; l >= rowBegin; l--) {
res.add(matrix[l][columnBegin]);
}
}
columnBegin++;
}
return res;
}
}