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, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
@tag-array

Algorithm

Define p and q to be the height and width of the current loop. When p or q is 1, it means that the last loop has only one row or one column, and you can jump out of the loop. The difficulty of this question lies in the conversion of subscripts. How to correctly convert subscripts is the key to solving this problem. You can complete the subscripts by referring to the 3x3 example above.